使用单例设计模式时,其他方法是否需要使用synced关键字来确保线程安全? [英] When using the singleton design pattern, do other methods need to use synchronized keyword to ensure thread safety?
本文介绍了使用单例设计模式时,其他方法是否需要使用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)
这篇关于使用单例设计模式时,其他方法是否需要使用synced关键字来确保线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文