简体   繁体   中英

Concurrency issue in a simple Java service

  1. In the below Java ToolHireService, how do I optimally prevent the concurrency issue where the same tool can get hired by more than one clients. It should only 'block the thread' when the same tool is being evaluated for hire.

  2. Any pointers on how to write a failing test?

public class ToolHireService {

    public int toolHire(Client client , String toolId , Date startDate , Date endDate){

        Tool tool = getToolFromDB(toolId);

        if(tool == null || tool.isHired()){
            return -1;
        }
        ToolHireEntry toolEntry = new ToolHireEntry(tool,startDate,endDate);
        client.addHireHistory(toolEntry);
        client.save();

        tool.setHired(true);
        return tool.save();

    }
}

PS: as long as different tools are being hired the bookings should be able to carry on uninterruptedly.

The answer as always, is it depends.

Do you have a single ToolHireInstance in one process which multiple clients are using? In this case it would be sufficient to simply syncronize the entire method.

Do you have multiple ToolHireInstances in one process which multiple clients are using? In this case you could synchronize on the ToolHireService.class object, which would create a single object all the instances would use to synchronize on.

Do you have multiple ToolHireInstances spread across multiple processes that each have clients (and your database has a JDBC connector)? In this case you would want to push the transactional part into JDBC by making the entire method exist in a SQL transaction. This would require reorganizing your code to expose a transaction element. You will need to decide what SQL isolation level is required to perform this atomic pull_tool->evaluate_status->save_hiring_decision.

Do you have multiple ToolHireInstances spread across multiple processes that each have clients (and no JDBC connector)? Consult your database on what kind of transaction methods exist. If none exist you'll need to use some other kind of external synchronization tool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM