If it is set to false, than the threads wait until one thread sets it to true. Your code doesn't wait until it's set to true - it just waits until it's notified. If someone calls setFlag(false) this will notify too, even though the flag is false.
You should probably replace
with
This code works fine.. but in some rare runs, the method checkFlag throws an InterruptedException.
Can someone explain me, why is this exception thrown and what can be done to prevent it. Most likely some other code somewhere is calling interrupt() on your thread. Do you call interrupt() anywhere? Are you running other software which might be calling it? It wouldn't surprise me if some
J2EE environments have thread pooling tools which might try to monitor the activity of their threads and interrupt them in certain circumstances - but I don't know details here, I'm just guessing.
Or is it a safe idea to put an empty catch block for this exception and ignore it. Well InterruptedException is one of the few cases where this may be a safe strategy - but usually only if you
know what other part of the code is calling interrupt(), and you know that it's OK. If you're not sure, I would say that you should at least log the exception so that you have the ability to investigate it later if necessary. If you hide the exception by ignoring it completely, you can make things much harder for yourself later.
You also need to decide just what behavior you need from this method. Does the method absolutely need to wait for flag to be true? Or if there's an interruption, should the method exit early (even though flag is false)? You might have code like this:
Here the InterruptedException allows the method to exit if flag is false. Proably this is a bad idea - if you want an early exit in this case, just allow the exceptino to be thrown; don't catch it. Because someone else (or even you) will probably assume that flag is true after this method completes, and it may not be. Or:
Here it doesn't matter if some other thread tries to interrupt; we're going to keep waiting until the flag is true, period. Which may be what you need, of may not. This is the sort of thing you need to decide though...