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

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 = "";
    }
}

}


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

Thread1
ElasticSearchClient elasticSearchClient = ElasticSearchClient.getInstance()
elasticSearchClient.createElasticIndex("firstindex");

Thread2
ElasticSearchClient elasticSearchClient = ElasticSearchClient.getInstance()
elasticSearchClient.createElasticIndex("secondindex");

Thread3...


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

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

最佳答案

在您的特定实现中

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:


checkIfElasticSearchIndexExists(index)如果T1和T2将使用相同的索引名称,则两者都将通过此检查(我仅假设这是一个rest调用-甚至更糟)
elasticConfig == null || elasticConfig.equals(BatchConstants.EMPTY_STRING)在第一个矮点T1和T2都将通过此测试,并且都将从文件中加载配置-可能不会产生影响,但仍然是赛车情况
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个线程可以查询相同的索引并获得完全相同的响应-该索引不存在并尝试创建一个。

08-04 08:11