如何在排队系统中获得下一个回合.同一部门的线程安全



我在java上做了一个函数,从数据库(PostgreSQL)表中获得下一个转弯。在获得下一个回合后,记录被更新,因此没有其他用户可以获得相同的回合。如果另一个用户请求next turn同时,有一个变化,下一回合都得到相同的. 所以第一个想法是同步功能,这样只有一个用户可以同时请求转弯。但是由于有多个部门,同一部门的两个用户不能同时请求turn,但是不同部门的两个用户可以同时请求turn,没有任何问题。

这是函数

的简化/伪代码
private DailyTurns callTurnLocal(int userId)
{
try {
DailyTurns turn = null;
DailyTurns updateTurn = null;

//get next turn for user (runs a query to the database)
turn = getNextTurnForUser(userId);
//found turn for user
if (turn != null)
{
//copy information from original record object to new one
updateTurn = turn;

//change status tu turn called
updateTurn.setTurnStatusId(TURN_STATUS_CALLED);
//add time for the event
updateTurn.setEventDate(new Date());

//update user that took the turn
updateTurn.setUserId(userId);

//save new record in the DB
updateTurn = save(updateTurn);
}

return updateTurn;
}
catch (Exception e)
{
logger.error( "Exception: " + e.getMessage(), e );

return null;
}
}

我知道我可以同步整个函数,但是如果来自不同部门的用户的两个或更多线程在下一个回合想要获得,则会减慢处理速度。. 如何添加每个部门的同步?或者是我可以在DB中实现的功能?

似乎更明显的解决方案是保留像ConcurrentHashMap这样的缓存,其中键被定义为部门。
这不会锁定整个对象,不同的线程可以并发地操作不同的部门。