【发布时间】:2015-01-25 02:38:19
【问题描述】:
我有一个包含表(哈希图)的单例对象(类)。所有其他对象(客户端)读取存储在表中的其他客户端列表。所有使用该表的方法都被同步关键字包围。我已经调试过表对于不同的客户有不同的值的情况。客户端可能在也可能不在同一个线程上运行,这就是我添加同步关键字的原因。
这里是使用 hashmap 的方法:
public synchronized Client addToConnectedClients(long key, Client client)
{
return allConnectedClients.put(key, client);
}
public synchronized Client getFromConnectedClients(long key)
{
return allConnectedClients.get(key);
}
public synchronized Client removeFromConnectedClients(long key)
{
return allConnectedClients.remove(key);
}
这是我从客户端对象内部访问表的方式:
Client temp=AppInterface.getInstance().getAppNetworkLogic().getFromConnectedClients(key);
AppNetowrkLogic 是 AppInterface 单例中的一个对象,它是在创建 AppInterface 时。
我不知道这是怎么发生的。
编辑:
这是getInstance 方法:
private static AppInterface instance=null;
public static AppInterface getInstance()
{
if(instance == null)
{
instance= new AppInterface();
}
return instance;
}
【问题讨论】:
-
你能显示 AppInterface.getInstance() 的代码吗?我怀疑那里有比赛条件。
-
我猜这就是为什么当前的单例模式是一个枚举。
标签: java multithreading synchronized volatile