开发者

Best way to get next turn in a queue system. Thread safe for same department

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?


Seems like a more obviously solution would be to keep a cache like ConcurrentHashMap where the keys are defined as department.
This won't lock the entire object and different threads can operate concurrently for different departments.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜