单例类的公共方法是否应该同步?

时间:2018-08-07 15:23:38

标签: java multithreading singleton

我有一个单例包装器类,为我的应用程序抽象了Elasticsearch API。

list_x name_1
list_y name_2
list_z name_3

我有多个使用ElasticSearchClient的线程,如下所述

public class ElasticSearchClient {    

    private static volatile ElasticSearchClient elasticSearchClientInstance;

    private static final Object lock = new Object();

    private static elasticConfig ; 

    /*
    ** Private constructor to make this class singleton
    */
    private ElasticSearchClient() {
    }

    /*
    ** This method does a lazy initialization and returns the singleton instance of ElasticSearchClient
    */
    public static ElasticSearchClient getInstance() {
        ElasticSearchClient elasticSearchClientInstanceToReturn = elasticSearchClientInstance;
        if (elasticSearchClientInstanceToReturn == null) {
            synchronized(lock) {
                elasticSearchClientInstanceToReturn = elasticSearchClientInstance;
                if (elasticSearchClientInstanceToReturn == null) {
                    // While this thread was waiting for the lock, another thread may have instantiated the clinet.
                    elasticSearchClientInstanceToReturn = new ElasticSearchClient();
                    elasticSearchClientInstance = elasticSearchClientInstanceToReturn;
                }
            }
        }
        return elasticSearchClientInstanceToReturn;
    }

    /*
    ** This method creates a new elastic index with the name as the paramater, if if does not already exists.
    *  Returns true if the index creation is successful, false otherwise.
     */
    public boolean createElasticIndex(String index) {
        if (checkIfElasticSearchIndexExists(index)) {
            LOG.error("Cannot recreate already existing index: " + index);
            return false;
        }
        if (elasticConfig == null || elasticConfig.equals(BatchConstants.EMPTY_STRING)) {
            loadElasticConfigFromFile(ELASTIC_CONFIG_FILE_NAME);
        }
        if (elasticConfig != null && !elasticConfig.equals("")) {
            try {
                HttpURLConnection elasticSearchHttpURLConnection = performHttpRequest(
                    ELASTIC_SEARCH_URL + "/" + index,
                    "PUT",
                    elasticConfig,
                    "Create index: " + index
                );

                return elasticSearchHttpURLConnection != null &&
                       elasticSearchHttpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK;
            } catch (Exception e) {
             LOG.error("Unable to access Elastic Search API. Following exception occurred:\n" + e.getMessage());
          }
        } else {
            LOG.error("Found empty config file");
        }
        return false;
    }

private void loadElasticConfigFromFile(String filename) {

    try {
        Object obj = jsonParser.parse(new FileReader(filename);
        JSONObject jsonObject = (JSONObject) obj;
        LOG.info("Successfully parsed elastic config file: "+ filename);
        elasticConfig = jsonObject.toString();
        return;
    } catch (Exception e) {
        LOG.error("Cannot read elastic config from  " + filename + "\n" + e.getMessage());
        elasticConfig = "";
    }
}

}

按照我的说法,Singleton类是线程安全的,但是我不确定如果多个线程开始执行与Singleton类相同的方法会发生什么。这有副作用吗?

注意:我知道上面的单例类不是反射和序列化安全的。

1 个答案:

答案 0 :(得分:1)

在您的特定实现中

if (checkIfElasticSearchIndexExists(index)) { //NOT THREAD SAFE
            LOG.error("Cannot recreate already existing index: " + index);
            return false;
        }
        if (elasticConfig == null || elasticConfig.equals(BatchConstants.EMPTY_STRING)) { //NOT THREAD SAFE
            loadElasticConfigFromFile(ELASTIC_CONFIG_FILE_NAME);
        }
        if (elasticConfig != null && !elasticConfig.equals("")) { //NOT THREAD SAFE

有3点可能会导致比赛状况。

就其本身

  

单例类公共方法应该同步吗?

没有这样的规则-如果那些规则是线程安全的,则不需要其他同步。在您的情况下,这些线程不是安全的,因此您必须使它们脱险。制作

public synchronized boolean createElasticIndex

如果您对例如并发写入单个索引的概念很了解,那就不要-这是ElasticSearch任务,可以正确处理并发写入(并且相信我,ES会顺利处理)

什么不是线程安全的(指出3个地方)?同时存在T1和T2:

  1. checkIfElasticSearchIndexExists(index)如果T1和T2将使用相同的索引名,则两者都将通过此检查(我仅假设这是一个rest调用-甚至更糟)
  2. elasticConfig == null || elasticConfig.equals(BatchConstants.EMPTY_STRING)首先,第一阶段T1和T2都将通过此测试,并且都将从文件中加载配置-可能不会产生影响,但仍然是赛车情况
  3. if (elasticConfig != null && !elasticConfig.equals(""))与2 +相同的情况(由于内存模型的原因),如果elasticConfig不是volatile,则在loadElasticConfigFromFile将其完全初始化之前,可以将其读取为“ not null”。

2和3可以通过两次检查锁定来固定(就像您在getInstance()中所做的那样,或者我宁愿将其移至实例初始化块中-构造函数将是我认为最好的。

为了更好地了解该现象,您可以检查why a==1 && a==2 can evaluate to true

1但是由于调用和响应之间的延迟而导致的问题更大,您得到了一个宽阔的窗口,其中2个线程可以查询相同的索引并获得完全相同的响应-该索引不存在并尝试创建一个。

相关问题