To extend the answer to โGrayโ: suppose you wanted to do this (determine when a method is used by multiple threads). A naive (and incorrect) implementation of this might look like this:
volatile boolean methodBeingUsed = false; public void doSomething() { if (methodBeingUsed) throw new IllegalStateException("You can't do that!"); try { methodBeingUsed = true;
OK, OK ... but two threads could pass the first if (methodBeingUsed) and enter the critical section at the same time. Now, perhaps we will try to add a lock to protect the methodBeingUsed flag:
Lock methodLock = new ReentrantLock(); volatile boolean methodBeingUsed = false; public void doSomething() { try { lock.lock(); if (methodBeingUsed) throw new IllegalStateException("You can't do that!"); methodBeingUsed = true; } finally { lock.unlock(); } try {
Of course, this suggests that doSomething () cannot call itself recursively. If possible, you should also monitor the calling thread. Add a few more checks to take into account other conditions that I donโt think about right now, and itโs easy to understand that the effort spent synchronizing the logic to find the method used by multiple threads is better spent just by making the -safe method thread start.
Alex
source share