Java ConcurrentHashMap用法

时间:2017-04-24 16:41:07

标签: java multithreading concurrenthashmap

我正在尝试在java中创建一个Map,其中key和value是指定的: Key =类DataSourceCredentials的对象

public class DataSourceCredentials {
String dataSourceName;
char[] password;
List<String> clusterNodes;
}

Value =类DataSourceConnector的对象

public class DataSourceConnector {
private static volatile ConcurrentMap<DataSourceCredentials, DataSourceConnector> map = new ConcurrentHashMap<DataSourceCredentials, DataSourceConnector>();
}

DataSourceCredentials的equals方法检查dataSourceName和clusterNodes但不检查密码。这是因为dataSource的密码可以改变。

我为类DataSourceConnector创建了下面的getInstance()方法,这样对于单个DataSourceCredentials值,只创建并返回一个DataSourceConnector实例。

public static DataSourceConnector getInstance(List<String> clusterNodes, String dataSourceName, char[] password) {
    try {

        DataSourceCredentials dataSource = new DataSourceCredentials(clusterNodes, dataSourceName, password );

        //check if DataSourceConnector already exists then return the same 
        for (DataSourceCredentials dataSourceCredential : map.keySet()) {
            if (dataSourceCredential.equals(dataSource)) {
                if ((password == null && dataSourceCredential.getPassword() == null) || (password != null
                        && dataSourceCredential.getPassword() != null && Arrays.equals(password, dataSourceCredential.getPassword()))) {
                    return map.get(dataSourceCredential);
                }
            }
        }


        DataSourceConnector connector = map.get(dataSource);    

        //if DataSourceConnector has not not been created then create one and return
        if(connector==null)
        {
            DataSourceConnector connector = new DataSourceConnector();
            return accessors.putIfAbsent(dataSource,connector); 
        }
        else  //if DataSourceConnector exists but password has changed/removed/added then create a new connector and return
        {
            synchronized(DataSourceConnector.class)
            {
                for (DataSourceCredentials dataSourceCredential : map.keySet()) {
                    if (dataSourceCredential.equals(dataSource) && ((password == null && dataSourceCredential.getPassword() != null)
                            || (!Arrays.equals(password, dataSourceCredential.getPassword())))) {
                        map.remove(dataSourceCredential);
                        DataSourceConnector connector = new DataSourceConnector();
                        return map.putIfAbsent(dataSource, connector);
                    }
                }
            }
        }
    }
    finally {
        if (password != null) {
            Arrays.fill(password, '\0');
        }
    }

    return null;
}

有人可以建议上述实施是否合适,是否有更好的方法可以做到这一点?

0 个答案:

没有答案