[并发]如果dao层是单例,怎么保证collection的线程安

2015-11-11  本文已影响335人  复苏森林
       
private static ThreadLocal<DBCollection> collectionHolderLocal = new ThreadLocal<DBCollection>() {  
    @Override
    protected DBCollection initialValue() {  
             return null;
    }
};
    
protected DBCollection collection() throws MMException {
    System.out.println(collectionHolderLocal);
    if(null == collectionHolderLocal.get()) {
        try {
              DBCollection collection = (DBCollection) MongoDBUtil.getDB().getCollection("dbname");
              collectionHolderLocal.set(collection);
        } catch (MMException e) {
              throw new Exception("连接数据库失败" + e.getMessage());
        }
    }
    return collectionHolderLocal.get();
}

上一篇 下一篇

猜你喜欢

热点阅读