本文介绍了静态是否在JMM上下文中提供其他保证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关Java单例的信息,遇到了奇怪的事情.

I am reading about java singleton and I've met strange things.

我将参考跟随artice 作为示例(您可以轻松找到更多)

I will refer to following artice as example(you can easy find more)

作者提供以下单例:

public class ASingleton {

    private static ASingleton instance = new ASingleton();

    private ASingleton() {
    }

    public static ASingleton getInstance() {            
        return instance;
    }

}

和评论:

缺点:
-及早创建可能在应用程序中未使用的资源.
-客户端应用程序无法传递任何参数,因此我们无法重复使用它.
例如,具有用于数据库连接的通用单例类
客户端应用程序在哪里提供数据库服务器属性.

Cons:
- Early creation of resource that might not be used in the application.
-The client application can’t pass any argument, so we can’t reuse it.
For example, having a generic singleton class for database connection
where client application supplies database server properties.

我想澄清没有同步的线程安全性点.

我已经在实践书中阅读了并发性,并且不记得与此相关的任何内容.

I've read concurrency in practice book and don't remember anything related with this.

我错过了一些东西,或者此说明不相关吗?

I missed something or this clarification is not relevant?

此外,我想告诉你,您可能会遇到相同的单例,但字段标记为static final,而不仅仅是static
PS

Additionally I want to tell you that you can encounter the same singleton but field marked as static final instead of just static
P.S.

我了解我可以阅读 JMM ,其中包含答案,但是我是平常的人,所以我不能理解这个来源.

I understand that I can read JMM and this one contains the answer but I am usual guy and I can't undertand this source.

推荐答案

相对于JMM来说,这种习惯用法是合理的.

That idiom is sound with respect to the JMM.

在类的静态初始化和任何静态变量的使用之间存在发生前的关系.这是在 JLS 12.4.2 .

There is a happens before relationship between the static initialization of a class and the use of any static variables. This is a consequence of the locking that occurs during the initailization procedure described in JLS 12.4.2.

根据我的阅读,此处不需要将instance声明为final即可获得所需的 happens-before .出于其他原因,建议这样做.

According to my reading, instance does not need to be declared as final here to get the required happens-before. It is advisable for other reasons though.

这篇关于静态是否在JMM上下文中提供其他保证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 03:24