Should I synchronize concurrent accesses to a Thread object aimed at interrupting it?

This question already has an answer here:

  • Do I need to synchronize a call to the interrupt method?

    3 answers

I have this kind of code:

class Foo {
    private final Thread mainThread = ...;
    public void start() { this.mainThread.start(); }
    public void stop() { this.mainThread.interrupt(); }

Note that Foo.mainThread is kind enough to check every now and then if it was interrupted by someone, and in the case it cleanly exits.

Now in my application there are many threads that share a Foo and are possibly interested in stopping it. Is everything OK or should I be paranoid and declare Foo.stop() to be a synchronized method?

Thread.interrupt basically just sets a flag. Certain operations, such as Thread.sleep will cause this flag to be checked, and an exception is thrown if the flag is set to true.

Provided you’re handling InterruptedExceptions
properly*, there’s no reason why two threads both setting the flag would be a problem.

So no. Don’t bother synchronizing stop.

You probably do want to synchronize start, though. Starting a thread twice will result in a IllegalThreadStateException. I’d re-write that function like so**:

private boolean started = false;

public void start()
    if (started) return;

        if (!started)
            started = true;

Here’s a good article which explains how Thread.interrupt works.

*By ‘properly’ I mean don’t do anything strange, like perform an operation which can throw an InterruptedException while you’re handling an InterruptedException. That would be silly.

**A simpler solution would synchronize the whole method, but may result in synchronizing too often. This way, we only synchronize if two threads both compete to start an un-started thread at exactly the same time, and never synchronize after that.