Synchronize On Same String Value [duplicate]

余生长醉 提交于 2020-06-12 02:48:06

问题


Let's say I have a method that creates a new user for a web application. The method itself calls a static helper class that creates a SQL statement that performs the actual insertion into my DB.

public void createUserInDb(String userName){
    SQLHelper.insertUser(userName);
}

I want to synchronize this method such that it cannot be called concurrently by different threads if the passed in parameter (userName) is the same on those threads. I know I can synchronize method execution using the synchronized keyword, but this would prevent different threads from concurrently executing the method in general. I only want to prevent concurrent execution if the passed in variable is the same. Is there an easy construct in Java that would let me do this?


回答1:


There is no guarantee that two strings with the same value would point to the same instance in Java, especially if they are created from user input.

However, you can easily force them into the string pool using the intern() method, which would guarantee it's the same instance being used:

public void createUserInDb(String userName){
    String interned = userName.intern();
    synchronized (interned) {
        SQLHelper.insertUser(interned);
    }
}


来源:https://stackoverflow.com/questions/31097134/synchronize-on-same-string-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!