How can you ensure in java that a block of code can not be interrupted by any other thread

Richard picture Richard · Dec 3, 2008 · Viewed 11.2k times · Source

exampl:

new Thread(new Runnable() {
  public void run() {
    while(condition) {

      *code that must not be interrupted*

      *some more code*
    }
  }
}).start();

SomeOtherThread.start();

YetAntherThread.start();

How can you ensure that code that must not be interrupted won't be interrupted?

Answer

Jon Skeet picture Jon Skeet · Dec 3, 2008

You can't - at least not with normal Java, running on a normal, non-real-time operating system. Even if other threads don't interrupt yours, other processes might well do so. Basically you won't be able to guarantee that you get a CPU all to yourself until you're done. If you want this sort of guarantee you should use something like Java Real-Time System. I don't know enough about it to know whether that would definitely provide the facility you want though.

The best thing to do is avoid that requirement in the first place.