Mục tiêu
Cho phép chủ động hủy instance Singleton (set về null) để buộc tạo mới lần sau truy cập, dùng cho: logout user, reset cache, thay đổi cấu hình lớn.
⚠️ Cảnh báo
Việc cho phép set instance = null phá vỡ tính "single" của Singleton. Chỉ dùng khi thực sự cần thiết (logout, reset app state).
Các bước thực hiện
Bước 1: Tạo dự án mới
Android Studio → File → New Project → Empty Activity.
Bước 2: Layout (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="24dp">
<Button
android:id="@+id/btnClearInstance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Xóa Singleton Instance" />
</LinearLayout>
Bước 3: SingleTonExample.java với clearInstance()
package com.example.singletonclear;
import android.content.Context;
public class SingleTonExample {
// Không dùng final để có thể gán null
private static SingleTonExample instance = new SingleTonExample();
private Context appContext;
private String data = "Dữ liệu mẫu: " + System.currentTimeMillis();
private SingleTonExample() {}
public static synchronized SingleTonExample getInstance() {
// Lazy re-initialization nếu instance bị null
if (instance == null) {
instance = new SingleTonExample();
}
return instance;
}
public void init(Context context) {
if (appContext == null) {
this.appContext = context.getApplicationContext();
}
}
public static Context getGlobalContext() {
return getInstance().appContext;
}
// PHƯƠNG THỨC CHÍNH: Xóa instance
public static synchronized void clearInstance() {
instance = null;
}
public String getData() {
return data;
}
}
Bước 4: MainActivity.java
package com.example.singletonclear;
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 Button btnClear;
private SingleTonExample singleton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnClear = findViewById(R.id.btnClearInstance);
singleton = SingleTonExample.getInstance();
singleton.init(getApplicationContext());
btnClear.setOnClickListener(v -> {
SingleTonExample.clearInstance();
Toast.makeText(this, "Đã xóa Singleton instance. Lần sau getInstance() sẽ tạo mới.", Toast.LENGTH_LONG).show();
});
}
}
Kết quả
Nhấn nút → Toast xác nhận. Lần sau gọi getInstance() sẽ tạo instance mới (data timestamp khác).


Khi nào nên clear Singleton?
- Logout user: Xóa session, token, profile data
- Chuyển môi trường: Dev → Staging → Production (config khác nhau)
- Reset cache: Dữ liệu lỗi thời, corrupted
- Test/Development: Khôi phục trạng thái ban đầu
Cách an toàn hơn: Reset nội bộ thay vì xóa instance
public static synchronized void resetData() {
if (instance != null) {
instance.dataMap.clear();
instance.data = "Reset lúc: " + System.currentTimeMillis();
}
}
Giữ nguyên instance (tránh null pointer ở chỗ đang giữ reference), chỉ reset dữ liệu bên trong.
Lưu ý thread-safety
- Dùng
synchronizedcho cảgetInstance()vàclearInstance() - Biến
instancenênvolatilenếu multi-thread đọc/ghi - Cân nhắc
AtomicReferencecho lock-free