Auto-Refresh Singleton Instance ทุก 1 ชั่วโมงด้วย Timer
บทความนี้สาธิตวิธีทำให้ Singleton Instance ตัวใหม่ถูกสร้างขึ้นทุก 1 ชั่วโมง โดยอัตโนมัติ เพื่อเคลียร์ข้อมูลเก่า/รีเซ็ตสถานะ ใช้ Timer และ TimerTask ร่วมกับ synchronized เพื่อ Thread Safety
⚠️ ข้อควรพิจารณา
การสร้าง Instance ใหม่ทุกชั่วโมงหมายถึง:
- ข้อมูลเก่าใน Instance เดิมจะหายไป (ถูก GC)
- Reference เก่าที่ถูกเก็บไว้ในที่อื่นจะชี้ไป Instance เก่า (Stale Reference)
- อาจเกิด Race Condition หากมี Thread กำลังใช้ Instance เดิม
แนะนำ: ใช้ clear() method แทนการสร้าง Instance ใหม่ หรือใช้ Cache Library (Room, DataStore) ที่รองรับ TTL/Expiration
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
Android Studio → File → New Project → Empty Activity
ขั้นตอนที่ 2: Layout - activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="24dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<TextView
android:id="@+id/tvInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Singleton จะ Refresh อัตโนมัติทุก 1 ชั่วโมง"
android:textSize="16sp"
android:textColor="#757575"
android:layout_marginBottom="16dp" />
<Button
android:id="@+id/btnShowStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="แสดงสถานะ Singleton" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
ขั้นตอนที่ 3: Singleton Class - AutoRefreshSingleton.java
package com.example.singletonrefreshdemo;
import android.content.Context;
import java.util.Timer;
import java.util.TimerTask;
public class AutoRefreshSingleton {
private static volatile AutoRefreshSingleton instance;
private static final Object LOCK = new Object();
private Context appContext;
private long creationTimestamp;
// Static Initialization Block - เริ่ม Timer ทันทีที่ Class โหลด
static {
Timer timer = new Timer(true); // true = daemon thread (ไม่บล็อก JVM shutdown)
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
synchronized (LOCK) {
// สร้าง Instance ใหม่แทนที่ตัวเก่า
instance = new AutoRefreshSingleton();
// Context จะต้อง init ใหม่เมื่อ getInstance() ถูกเรียกครั้งต่อไป
}
}
}, 60 * 60 * 1000L, 60 * 60 * 1000L); // Delay 1 ชม., Period 1 ชม.
}
private AutoRefreshSingleton() {
this.creationTimestamp = System.currentTimeMillis();
}
public static AutoRefreshSingleton getInstance() {
if (instance == null) {
synchronized (LOCK) {
if (instance == null) {
instance = new AutoRefreshSingleton();
}
}
}
return instance;
}
public void init(Context context) {
if (appContext == null) {
this.appContext = context.getApplicationContext();
}
}
public Context getContext() {
return appContext;
}
public static Context getGlobalContext() {
return getInstance().getContext();
}
public long getCreationTime() {
return creationTimestamp;
}
public String getStatus() {
long ageMinutes = (System.currentTimeMillis() - creationTimestamp) / (60 * 1000);
return "Instance สร้างเมื่อ: " + new java.text.SimpleDateFormat("HH:mm:ss").format(new java.util.Date(creationTimestamp))
+ "\nอายุ: " + ageMinutes + " นาที";
}
}
ขั้นตอนที่ 4: MainActivity.java
package com.example.singletonrefreshdemo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private AutoRefreshSingleton singleton;
private Button btnShowStatus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
singleton = AutoRefreshSingleton.getInstance();
singleton.init(getApplicationContext());
btnShowStatus = findViewById(R.id.btnShowStatus);
btnShowStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String status = singleton.getStatus();
Toast.makeText(MainActivity.this, status, Toast.LENGTH_LONG).show();
}
});
}
}
ปัญหาของการสร้าง Instance ใหม่ (Stale Reference Problem)
// ในคลาสอื่นที่เก็บ reference ไว้
public class SomeManager {
private AutoRefreshSingleton cachedInstance = AutoRefreshSingleton.getInstance();
public void doWork() {
// อันตราย! cachedInstance อาจเป็น Instance เก่าที่ถูกแทนที่แล้ว
cachedInstance.doSomething(); // ใช้ข้อมูลเก่า/Instance ที่ควรจะถูก GC
}
}
วิธีแก้: ใช้ Clear Method แทน (แนะนำ)
public class BetterSingleton {
private static volatile BetterSingleton instance;
private final Map<String, Object> cache = new ConcurrentHashMap<>();
private Context appContext;
private BetterSingleton() {}
public static BetterSingleton getInstance() { ... }
public void init(Context context) { ... }
// แทนที่การสร้าง Instance ใหม่ ให้ Clear ข้อมูลภายใน
public void refresh() {
cache.clear();
// reset อื่นๆ
}
// Scheduled Refresh - เรียกจาก Application หรือ WorkManager
public static void scheduleHourlyRefresh(Context context) {
// ใช้ WorkManager แทน Timer (เหมาะกว่า)
PeriodicWorkRequest refreshWork = new PeriodicWorkRequest.Builder(
RefreshWorker.class, 1, TimeUnit.HOURS)
.build();
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
"singleton_refresh", ExistingPeriodicWorkPolicy.KEEP, refreshWork);
}
}
// Worker สำหรับ Refresh
public class RefreshWorker extends CoroutineWorker {
public RefreshWorker(@NonNull Context context, @NonNull WorkerParameters params) {
super(context, params);
}
@NonNull
@Override
public Result doWork() {
BetterSingleton.getInstance().refresh();
return Result.success();
}
}
การทดสอบ (เร่งเวลาสำหรับ Demo)
เปลี่ยน Timer ให้รันทุก 10 วินาที แทน 1 ชั่วโมง:
timer.scheduleAtFixedRate(new TimerTask() { ... }, 10000, 10000); // 10 วินาที
สรุป
การ Refresh Singleton โดยการสร้าง Instance ใหม่เป็นแนวคิดที่น่าสนใจ แต่มีความเสี่ยงด้าน Stale Reference ควรใช้วิธี Clear Internal State แทน และจัดการ Scheduling ด้วย WorkManager ซึ่งทนทานต่อ Reboot และ Doze Mode