7

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?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
jason.zissman
  • 2,750
  • 2
  • 19
  • 24

1 Answers1

7

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);
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 2
    Interning strings like this is, however, not a good idea. It can cause a memory leak - strings that are interned in the string pool stay there until the JVM exits. – Jesper Jun 28 '15 at 07:26
  • 3
    @Jesper That hasn't been true for a considerable number of years. Interned strings can be garbage-collected just like the others. See [this answer](http://stackoverflow.com/a/18153570/207421) and my comments on [this one](http://stackoverflow.com/a/2431597/207421), heavily upvoted. – user207421 Jun 28 '15 at 07:39
  • 2
    @EJP the behaviour of `String.intern()` depends on the JVM Version. The behaviour of `String.intern` is very the different for JVM 6,7,8 see for example the blog of [Mikhail Vorontsov - String.intern in Java 6, 7 and 8 – string pooling](http://java-performance.info/string-intern-in-java-6-7-8/). Or for some more details have a look at http://bugs.sun.com/view_bug.do?bug_id=6962931 and http://bugs.sun.com/view_bug.do?bug_id=6962930. – andih Jun 28 '15 at 07:49