- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个线程安全的 Singleton 类,我需要锁定它的方法吗?
private static volatile JsonWriter instance;
private static final Object mutex = new Object();
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private JsonWriter() {
}
public static JsonWriter getInstance() {
JsonWriter result = instance;
if (result == null) {
synchronized (mutex) {
result = instance;
if (result == null) {
instance = result = new JsonWriter();
}
}
}
trả về kết quả;
}
是否需要像这样锁定每个方法以确保线程安全?
public void write(String filePath, ArrayNode content) throws IOException {
lock.writeLock().lock();
File file = new File(MASTER_DIR + "/" + filePath);
mapper.writerWithDefaultPrettyPrinter().writeValue(Files.newOutputStream(file.toPath()), content);
}
1 Câu trả lời
性能最好且线程安全的 Singleton 实现是 William Pugh Singleton。您不需要同步块(synchronized block)和ReentrantReadWriteLock
.
William Pugh 实现可确保多线程安全和最佳性能,因为它避免了急于创建。事实上,在类级别初始化的静态成员 INSTANCE 仅在类加载器加载嵌套类时(即实际使用嵌套类时)才会创建。在以下实现中,只有在调用 getInstance()
方法时才会发生这种情况。事实上,与 EagerSingleton 相反,该模型实际上允许使用封闭类,而不会导致急切的实例化。这意味着封闭类提供的任何其他方法都可以安全地使用,而无需初始化INSTANCE
;只有 getInstance()
方法会导致它。
您的实现可能如下所示:
class JsonWriter {
private JsonWriter() {}
/* ... other methods ... */
public static JsonWriter getInstance() {
return SingletonHelper.INSTANCE;
}
private static class SingletonHelper {
private static final JsonWriter INSTANCE = new JsonWriter();
}
}
特别感谢@Holger,他在评论中提供了重要的澄清和评论。
关于java - 线程安全单例、锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72449405/
我最近购买了《C 编程语言》并尝试了 Ex 1-8这是代码 #include #include #include /* * */ int main() { int nl,nt,nb;
早上好!我有一个变量“var”,可能为 0。我检查该变量是否为空,如果不是,我将该变量保存在 php session 中,然后调用另一个页面。在这个新页面中,我检查我创建的 session 是否为空,
我正在努力完成 Learn Python the Hard Way ex.25,但我无法理解某些事情。这是脚本: def break_words(stuff): """this functio
Tôi là một lập trình viên xuất sắc, rất giỏi!