Java – synchronize on values, not objects
•
Java
I want to do this in Java
public void giveMoney(String userId,int money) { synchronized (userId) { Profile p = fetchProfileFromDB(userId); p.setMoney(p.getMoney() + userId); saveProfileToDB(p); } }
But of course, string synchronization is incorrect What is the right way to do such a thing?
Solution
If the user ID collection is limited, you can synchronize on the build string
Use string Intern () (it has some drawbacks) or something like guava interners if you need more control internships
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码