Sync with same string value

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 an SQL statement that performs the actual installation in my database.

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

I want to synchronize this method so that it cannot be called simultaneously by different threads if the passed parameter ( userName) is the same in these threads . I know that I can synchronize the execution of a method using the synchronized keyword, but this would prevent different threads from executing this method simultaneously. I want to prevent simultaneous execution if the passed variable is the same. Is there a simple construct in Java that would allow me to do this?

+4
source share
1 answer

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

intern(), :

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

All Articles