Java synchronization is based on parameters

I am looking for a way to synchronize the method based on the received parameters, as follows:

public synchronized void doSomething(name){
//some code
}

I want the dosomething method to synchronize based on the name parameter:

Thread 1: dosomething ("a");

Thread 2: dosomething ("B");

Thread 3: dosomething ("C");

Thread 4: dosomething ("a");

Thread 1, thread 2 and thread 3 will execute code out of sync, but thread 4 will wait for thread 1 to complete the code because it has the same "a" value

thank you

UPDATE

Based on Tudor's explanation, I think I face another problem: here is an example of the new code:

private HashMap locks=new HashMap();
public void doSomething(String name){
    locks.put(name,new Object());
    synchronized(locks.get(name)) {
        // ...
    }
    locks.remove(name);
}

The reason I don't populate the lock graph is because names can have any value

Based on the above example, since HashMap is not thread safe, this problem may occur when adding / deleting values in HashMap from multiple threads at the same time

So my problem is that if I make the HashMap a concurrent HashMap, which is thread safe, the synchronization block will prevent other threads from accessing locks get(name)?

Solution

Use the map to associate a string with a locked object:

Map<String,Object> locks = new HashMap<String,Object>();
locks.put("a",new Object());
locks.put("b",new Object());
// etc.

then:

public void doSomething(String name){
    synchronized(locks.get(name)) {
        // ...
    }
}
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
分享
二维码
< <上一篇
下一篇>>