Multiton模式使用的副作用

时间:2014-03-13 09:52:03

标签: java design-patterns concurrency multiton

我需要你的建议,代码审查或改进我的多模式模式实现。我想为mongodb服务器提供多连接支持。

public class MongoDatabaseFactory {
    private static volatile Map<String, MongoDatabase> connections = new ConcurrentHashMap<String, MongoDatabase>();

    public static MongoDatabase getDatabase(Databases database) throws MongoException {
        if (null == database) throw new MongoException("Database not found");
        if (null == database.name() || database.name().isEmpty()) throw new MongoException("Database not found");

        if (!connections.containsKey(database.name()) || null == connections.get(database.name())) {
            synchronized (database) {
                if (!connections.containsKey(database.name()) || null == connections.get(database.name())) {
                    connectDB(database);
                }
            }
        }

        if (!connections.get(database.name()).isAuthenticated()) {
            synchronized (database) {
                if (!connections.get(database.name()).isAuthenticated()) {
                    connectDB(database);
                }
            }
        }

        return connections.get(database.name());
    }
}

多重模式的最佳做法是什么?

2 个答案:

答案 0 :(得分:1)

正如 Marko Topolnik 所说,您当前的解决方案不是线程安全的。

我把它作为一个小练习,并编写了以下通用线程安全的Multition模式。它是否适用于许多线程,并且适用于价值对象创建昂贵的情况。请注意,我不确定在您的具体情况下是否有更简单的解决方案。

import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;


public class ThreadSafeMultition <K, V> {
  private final ConcurrentHashMap<K, FutureTask<V>> map = new ConcurrentHashMap<K, FutureTask<V>>();
  private ValueFactory<K, V> factory;

  public ThreadSafeMultition(ValueFactory<K, V> factory) {
    this.factory = factory;
  }

  public V get(K key) throws InterruptedException, ExecutionException {
    FutureTask<V> f = map.get(key);
    if (f == null) {
      f = new FutureTask<V>(new FactoryCall(key));
      FutureTask<V> existing = map.putIfAbsent(key, f);
      if (existing != null)
        f = existing;
      else // Item added successfully. Now that exclusiveness is guaranteed, start value creation.
        f.run();
    } 

    return f.get();
  }

  public static interface ValueFactory<K, V> {
    public V create(K key) throws Exception;
  }

  private class FactoryCall implements Callable<V> {
    private K key;

    public FactoryCall(K key) {
      this.key = key;
    }

    @Override
    public V call() throws Exception {
      return factory.create(key);
    }    
  }
}

答案 1 :(得分:0)

这一行不是线程安全的:

if (!connections.containsKey(database.name()) || null == connections.get(database.name()))

您将在哈希地图上进行数据竞争,因为您没有使用锁保护地图访问。可能最好的解决方案是将其移入synchronized块。你不应该担心这里的表现,至少没有坚定的证据。