Extend Thread to test proper termination with join?

ctomek :

Java Concurrency In Practice, 12.1.2. Testing Blocking Operations:

void testTakeBlocksWhenEmpty() {
 final BoundedBuffer<Integer> bb = new BoundedBuffer<Integer>(10);
 Thread taker = new Thread() {
  public void run() {
   try {
    int unused = bb.take();
    fail(); // if we get here, it’s an error
   } catch (InterruptedException success) { }
  }
 };
 try {
  taker.start();
  Thread.sleep(LOCKUP_DETECT_TIMEOUT);
  taker.interrupt();
  taker.join(LOCKUP_DETECT_TIMEOUT);
  assertFalse(taker.isAlive());
 } catch (Exception unexpected) {
  fail();
 }
}

This is one of the few cases in which it is appropriate to subclass Thread explicitly instead of using a Runnable in a pool: in order to test proper termination with join. The same approach can be used to test that the taker thread unblocks after an element is placed in the queue by the main thread.

But I don't see how extending Thread helps with testing that. For me it seems that the same test could be done with passing Runnable to Thread. Can somebody explain that?

Aleksandr Semyannikov :

This is one of the few cases in which it is appropriate to subclass Thread explicitly instead of using a Runnable in a pool: in order to test proper termination with join.

In other words that approach lets you a chance to interrupt the test thread and join it to make sure it has been terminated properly. You can't handle threads in that way if you use, for example - ThreadPoolExecutor class.

Also, it is OK to create a new thread, initiating it with Runnable, like Thread taker = new Thread(() -> {...});. Remember that the book was written about 8 years ago, and creating Runnable instead of subclass of Thread would make that example a bit longer.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=107340&siteId=1