Reputation: 473
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
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