20

Java-based synchronization based on a parameter

 3 years ago
source link: https://www.codesd.com/item/java-based-synchronization-based-on-a-parameter.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Java-based synchronization based on a parameter

advertisements

I'm looking for a way to synchronize a method based on the parameter it receives, something like this:

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

I want the method doSomething to be synchronized based on the name parameter like this:

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 the code without being synchronized , but Thread 4 will wait until Thread 1 has finished the code because it has the same "a" value.

Thanks

UPDATE

Based on Tudor explanation I think I'm facing another problem: here is a sample 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 why I don't populate the locks map is because name can have any value.

Based on the sample above , the problem can appear when adding / deleting values from the hashmap by multiple threads in the same time, since HashMap is not thread-safe.

So my question is if I make the HashMap a ConcurrentHashMap which is thread safe, will the synchronized block stop other threads from accessing locks.get(name) ??


Use a map to associate strings with lock objects:

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)) {
        // ...
    }
}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK