在下面的代码中;由于系统级锁定(addConfLock),在将新会议(addConference()API)添加到集合中时,许多线程在我的系统中被阻塞。添加每个新会议线程为BLOCKED;添加conf的时间增加,因为必须通过执行复杂的sql从DB创建/构建每个会议对象。所以Thread BLOCKING时间与DB Transaction成正比。
我想将conf对象创建与SYNC块分开,将conf添加到集合中 我试过一个解决方案;如果有任何其他解决方案,请指导我或解释我对我的解决方案的不好。
以下是原始代码。
class Conferences extends OurCollectionImpl
{
//Contains all on going conferences
}
//single conference instance
class Conf {
String confId;
Date startTime;
Date participants;
public void load()
{
// Load conference details from DB, and set its instance memebrs
}
}
class ConfMgr
{
Conferences confs = new Conferences();
Object addConfLock = new Object();
public boolean addConference(DBConn conn, String confID){
synchronized(addConfLock) {
Conf conf = null;
conf = confs.get(confID)
if(conf != null)
{ return true;}
conf = new Conf();
conf.setConfID(confId);
conf.load(); //This is the BIG JOB with in SYNC BLOCK NEED TO SEPARATED
confs.add(conf);
}
}
}
//我的解决方案
public boolean addConference(DBConn conn, String confID){
Conf conf = null;
synchronized(addConfLock) {
conf = confs.get(confID)
if(conf != null)
{ return true;}
conf = Conf.getInstance(confID, conn);
}
synchronized(conf.builded) { //SYNC is liberated to individual conf object level
if(conf.builded.equals("T")) {
return true;
}
conf.load();
synchronized(addConfLock) {
confs.add(conf);
}
conf.builded = "T";
}
}
}
//single conference instance
class Conf {
String confId;
Date startTime;
Date participants;
String builded = "F"; //This is to avoid building object again.
private static HashMap<String, Conf> instanceMap = new HashMap<String, Conf>;
/*
* Below code will avoid two threads are requesting
* to create conference with same confID.
*/
public static Conf getInstance(DBConn conn, String confID){
//This below synch will ensure singleTon created per confID
synchronized(Conf.Class) {
Conf conf = instanceMap.get(confID);
if(conf == null) {
conf = new Conf();
instanceMap.put(confID, conf);
}
return conf;
}
}
public void load()
{
// Load conference details from DB, and set its instance memebrs
}
}
答案 0 :(得分:0)
您所说的问题是您为每个配置锁定了所有内容。 如何更改锁定机制的设计,以便每个conf id都有单独的锁定,那么只有当事务是针对相同的conf id时才会锁定,否则执行将是并行的。
以下是你如何实现它:
Conferences
应该使用COncurrentHashMap存储不同的conf。conf = confs.get(confID)
检索的conf对象,即synchronize(conf)。您的应用程序应该表现得更好。
编辑:
问题在于此代码:
synchronized(addConfLock) {
conf = confs.get(confID)
if(conf != null)
{ return true;}
conf = Conf.getInstance(confID, conn);
}
如果你使用ConcurrentHashMap
作为集合,你可以删除它,它提供了一个api putIfAbsent
,所以你不需要锁定它。