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

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


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.


Assuming you're only concerned with application-level thread contention, and assuming you are willing to fuss with locks as suggested by others (which, IMHO, is a really bad idea), then you should use a ReadWriteLock and not simple object synchronization:

import java.java.util.concurrent.locks.*;// create a fair read/write lockfinal ReadWriteLock rwLock = new ReentrantReadWriteLock(true);// the main thread grabs the write lock to exclude other threadsfinal Lock writeLock = rwLock.writeLock();// All other threads hold the read lock whenever they do // *anything* to make sure the writer is exclusive when // it is running. NOTE: the other threads must also // occasionally *drop* the lock so the writer has a chance // to run!final Lock readLock = rwLock.readLock();new Thread(new Runnable() {  public void run() {    while(condition) {      writeLock.lock();      try {        *code that must not be interrupted*      } finally {        writeLock.unlock();      }      *some more code*    }  }}).start();new SomeOtherThread(readLock).start();new YetAntherThread(readLock).start();


Actually, you can do this if you control the thread instance you are running on. Obviously, there are a ton of caveats on this (like hanging io operations), but essentially you can subclass Thread and override the interrupt() method. you can then put some sort of boolean in place such that when you flip a flag, interrupt() calls on your thread are either ignored or better yet stored for later.