這些方法是getNewId()
& fetchIdsInReserve()
線程安全嗎?此方法線程安全嗎?
public final class IdManager {
private static final int NO_OF_USERIDS_TO_KEEP_IN_RESERVE = 200;
private static final AtomicInteger regstrdUserIdsCount_Cached = new AtomicInteger(100);
private static int noOfUserIdsInReserveCurrently = 0;
public static int getNewId(){
synchronized(IdManager.class){
if (noOfUserIdsInReserveCurrently <= 20)
fetchIdsInReserve();
noOfUserIdsInReserveCurrently--;
}
return regstrdUserIdsCount_Cached.incrementAndGet();
}
private static synchronized void fetchIdsInReserve(){
int reservedInDBTill = DBCountersReader.readCounterFromDB(....); // read column from DB
if (noOfUserIdsInReserveCurrently + regstrdUserIdsCount_Cached.get() != reservedInDBTill) throw new Exception("Unreserved ids alloted by app before reserving from DB");
if (DBUpdater.incrementCounter(....)) //if write back to DB is successful
noOfUserIdsInReserveCurrently += NO_OF_USERIDS_TO_KEEP_IN_RESERVE;
}
}
'//從數據庫中取數據...'代碼是否容易被其他線程阻塞?特別是,其他線程已經開始做一些數據庫的東西,然後*然後*想獲得一個新的ID?如果是這樣,你可能會讓自己陷入僵局。 – cHao 2012-03-31 21:27:06
,因爲對該方法的調用只是通過'getNewId()'中的同步塊來實現的。我相信這種方法一次只能被一個線程調用嗎? – 2012-03-31 21:29:00
我假設這不是唯一的代碼,你會碰到一個數據庫...其他代碼可能會獲得鎖等。 – cHao 2012-03-31 21:30:25