In our system, we have a method that will do some work when it\'s called with a certain ID:
public void doWork(long id) { /* ... */ }
Now, this
You can try the following little 'hack'
String str = UNIQUE_METHOD_PREFIX + Long.toString(id);
synchornized(str.intern()) { .. }
which is 100% guaranteed to return the same instance.
The UNIQUE_METHOD_PREFIX
, may be a hardcoded constant, or may be obtained using:
StackTraceElement ste = Thread.currentThread().getStackTrace()[0];
String uniquePrefix = ste.getDeclaringClass() + ":" +ste.getMethodName();
which will guarantee that the lock happens only on this precise method. That's in order to avoid deadlocks.