I did a function on java to get the next turn from a database (PostgreSQL) table. After getting the next turn, the record is updated so no other user can get the same turn. If another users request next turn at the same time, there is a change that both get the same next turn. So firt idea is to syncronize the function so only one user can request turn at the same time. But there are several departments, so two users from the same department cannot request turn at the same time, but two users from diferent departments could without any issue.
This is a simplified / pseudocode of the function
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;
}
}
I'm aware that I can syncronize the entire function, but that would slow process if two or more threads from users in different departments want to get next turn. How can I add syncronization per department? Or is something that I can achieve with a function in the DB?
1条答案
按热度按时间nr9pn0ug1#
看起来一个更明显的解决方案是保留一个像
ConcurrentHashMap
这样的缓存,其中的键被定义为部门。这不会锁定整个对象,不同的线程可以为不同的部门并发操作。