0

我需要您对我的 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());
    }
}

多吨模式的最佳实践是什么?

4

2 回答 2

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);
    }    
  }
}
于 2014-03-13T11:07:08.367 回答
0

此行不是线程安全的:

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

您将在此处对哈希映射进行数据竞争,因为您没有使用锁保护映射访问。可能最好的解决方案是将其移动到synchronized块中。你不应该担心这里的表现,至少在没有确凿证据的情况下是这样。

于 2014-03-13T10:18:26.073 回答