gpt4 book ai didi

java - 多模式使用的副作用

转载 作者:行者123 更新时间:2023-12-01 13:17:10 25 4
gpt4 key购买 nike

我需要您对我的多实例模式实现提出建议、代码审查或改进。我想要 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());
}
}

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

最佳答案

正如 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);
}
}
}

关于java - 多模式使用的副作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22374769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com