使用单例设计模式时,其他方法是否需要使用synced关键字来确保线程安全?
问题描述:
我想确保以下类是线程安全的,是否应将synced关键字用于其他方法?或使用线程安全的数据结构存储电子邮件。我该怎么办?
I want to ensure that the following class is thread-safe, should I use the synchronized keyword for other methods? Or use a thread-safe data structure to store Email. What should I do?
public class RecycleStation {
private static volatile RecycleStation uniqueInstance;
private static List<Email> recycleEmailList ;
private RecycleStation() {
recycleEmailList = new ArrayList<>();
}
public static RecycleStation getInstance() {
if (uniqueInstance == null) {
synchronized (RecycleStation.class) {
if (uniqueInstance == null) {
uniqueInstance = new RecycleStation();
}
}
}
return uniqueInstance;
}
public void RecycleEmail(Email email) {
recycleEmailList.add(email);
}
public void deleteEmail(Email email) {
recycleEmailList.remove(email);
}
public void clear() {
recycleEmailList.clear();
}
}
答
首先,最好将Singleton模式实现为Java中的Enum
其次,每个电子邮件
操作功能(清除
,回收
,删除
)应同步以确保线程安全(该链接是一个枚举,但是每个Sinlgeton实现都相同):
First, a Singleton pattern is best implemented as Enum in Java
Second, each email
manipulation function (clear
, Recycle
, delete
) should be synchronized to ensure thread safety (the link is about an Enum, but the same holds about each and every Sinlgeton implementation):
public synchronized void RecycleEmail(Email email)