user39950
user39950

Reputation: 473

Using a Java map safely as mutex holder

Requirement is, that relevant code within method A is not executed in parallel on any Object with the same class.

Will following pseudo code do it?

 private final Map<String, Object> simpleMutex = new HashMap<>();
 
 public void A( final Object o)
  {
    final ThreadLocal<Object> myLock = new ThreadLocal<>();
    synchronized ( simpleMutex )
    {
      myLock.set( simpleMutex.computeIfAbsent( o.getClass().getName(), className-> new Object() ) );
    }

    synchronized ( myLock.get() )
    {
      System.out.println("Executing A on " + o);
    }
  }

Upvotes: 0

Views: 326

Answers (1)

Daniel Zin
Daniel Zin

Reputation: 499

private final Map<Class<?>, Object> locksMap = new ConcurrentHashMap<>();

public void A(final Object o) {
     Object myLock = locksMap.computeIfAbsent(o.getClass(), className -> new Object());
     synchronized (myLock) {
          System.out.println("Executing A on " + o);
     }
}

Upvotes: 1

Related Questions