ahrooran
ahrooran

Reputation: 1116

Calling the instance to the thread inside that same thread

Context:

I have a cmd application in java which is written to work in peer-to-peer mode in different servers. Once a server starts, all other instances must stop. So I have written a piece of code that runs in a low priority thread and monitors an AtomicBoolean value autoClose, and whenever autoClose is set to true, thread will close application. (P.S.: I don't want to manually add close because the application has 2 main high priority threads and many temporary normal priority threads).

Here is the code:

/**
 * Watches autoClose boolean value and closes the connector once it is true
 * <p>
 * This is a very low priority thread which continuously monitors autoClose
 */
protected void watchAndClose() {
    Thread watchAutoClose = new Thread(() -> {
        while (true) {

            if (autoClose.get()) {
                close();

                // wait till closing is successful
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException ignored) {

                    // I want instance of thread watchAutoClose so I can call this
                    // watchAutoClose.interrupt();

                }
                if (!component.getStatus()) setAutoClose(false);
            }
        }
    });
    watchAutoClose.setPriority(Thread.MIN_PRIORITY);
    watchAutoClose.start();
}

Question:

SonarLint says I can't leave InterruptedException part empty. I have to either throw it again or call thatThread.interrupt().

So how can I do this? I want an instance of thread watchAutoClose inside that thread so I can call watchAutoClose.interrupt(). I tried Thread.currentThread() but I fear with that many threads, the currently executing thread wouldn't be this thread. (i.e, there is a possibility of JVM can choose to switch to another thread by the time it is inside the catch clause and calls Thread.currentThread() so at that time current thread would be the other one and I would interrupt that other thread... correct me if I am too worrying or my concept is totally wrong.)

Or should I ignore the warning altogether and leave catch block?

Upvotes: 1

Views: 70

Answers (1)

Holger
Holger

Reputation: 298389

First of all, it’s not clear why you think that waiting for a second was necessary at all. By the time, the close() method returns, the close() method has been completed. On the other hand, if close() truly triggers some asynchronous action, there is no guaranty that waiting one second will be sufficient for its completion.

Further, addressing your literal question, Thread.currentThread() always return the calling thread’s instance. It’s impossible for a thread to execute that method without being in the running state. When a task switch happens, the thread can’t read the reference at all, until it gets CPU time again. Besides that, since the specification says that this method returns the Thread instance representing the caller, the environment has to ensure this property, regardless of how it implements it. It works even when multiple threads call this method truly at the same time, on different CPU cores.

So, regardless of how questionable the approach of waiting a second is, handling interruption like

try {
    TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException ignored) {
    Thread.currentThread().interrupt();
}

is a valid approach.

But you may also replace this code with

LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));

The parkNanos method will return silently on interruption, leaving the calling thread in the interrupted state. So it has the same effect as catching the InterruptedException and restoring the interrupted state, but is simpler and potentially more efficient as no exception needs to be constructed, thrown, and caught.

Another point is that you are creating a polling loop on the atomic variable consuming CPU cycles when the variable is false, which is discouraged, even when you give the thread a low priority.

Upvotes: 3

Related Questions