2

Here is the snippet from book Java Concurrency in Practice:

//Scheduling an interrupt on a borrowed thread. Don’t do this.

private static final ScheduledExecutorService cancelExec = ...;

public static void timedRun(Runnable r,long timeout, TimeUnit unit) {
    final Thread taskThread = Thread.currentThread();
    cancelExec.schedule(new Runnable() {
        public void run() { taskThread.interrupt(); }
    }, timeout, unit);
    r.run();
}

The author says:

This is an appealingly simple approach, but it violates the rules: you should know a thread’s interruption policy before interrupting it. Since timedRun can be called from an arbitrary thread, it cannot know the calling thread’s interruption policy. If the task completes before the timeout, the cancellation task that interrupts the thread in which timedRun was called could go off after timedRun has returned to its caller. We don’t know what code will be running when that happens, but the result won’t be good. (It is possible but surprisingly tricky to eliminate this risk by using the ScheduledFuture returned by schedule to cancel the cancellation task.)

Further, if the task is not responsive to interruption, timedRun will not return until the task finishes, which may be long after the desired timeout (or even not at all). A timed run service that doesn’t return after the specified time is likely to be irritating to its callers.

My questions:

  1. What does timeout mean?
  2. What is cancellation task?
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
user2916610
  • 765
  • 1
  • 5
  • 12

1 Answers1

3

The timeout means that taskThread has an allotted time interval to run the task before it gets interrupted. The cancellation task is the dedicated task that does the interrupting (on a separate thread).

Dangers here are:

  • The code is interrupting a thread rather than cancelling a task. The thread being interrupted might be part of a thread pool and could have finished the task already and be in the middle of some entirely different task.

  • The task being interrupted might not use the interruption appropriately as an indicator to finish up its work, or if could be doing something like blocking I/O where it can't check the interrupt status, so there's no assurance in general that the timeout is effective.

Daniel Le
  • 1,800
  • 1
  • 14
  • 23
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
  • I think "The timeout means that the **thread** has an alloted time interval for the thread to run in" should be "The timeout means that the **task** has an alloted time interval for the thread to run in". And what is alloted? – Jason Law Jan 02 '20 at 02:52