Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronize On Same String Value [duplicate]

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?

like image 977
jason.zissman Avatar asked Jun 28 '15 07:06

jason.zissman


People also ask

Is synchronized method more efficient?

If you synchronize a code block within that method then more than one thread can execute the method simultaneously, but only one thread can enter the synchronized block at a time. From this we can conclude that synchronizing on the smallest possible code block required is the most efficient way to do it.

What is string synchronization?

Thread synchronizationIf a process has multiple threads running independently at the same time (multi-threading) and if all of them trying to access a same resource an issue occurs. To resolve this, Java provides synchronized blocks/ synchronized methods.

Can two synchronized methods in same class?

Yes, they can run simultaneously both threads. If you create 2 objects of the class as each object contains only one lock and every synchronized method requires lock.

What are two methods of synchronization?

There are two types of synchronization: data synchronization and process synchronization: Process Synchronization: The simultaneous execution of multiple threads or processes to reach a handshake such that they commit a certain sequence of actions. Lock, mutex, and semaphores are examples of process synchronization.


1 Answers

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);
    }
}
like image 147
Mureinik Avatar answered Oct 11 '22 07:10

Mureinik