开发者

Java concurrency in practice - Listing 5.11

In JCiP book, at listing 5.11, is this code will wait forever if any of Thread t is interrupted (because startGate.await() can throw InterruptedException) so endGate latch will never be released ?

public class TestHarness { 
public long timeTasks(int nThreads, final Runnable task) 
        throws InterruptedException { 
    final CountDownLatch startGate = new CountDownLatch(1); 
    final CountDownLatch endGate = new CountDownLatch(nThreads); 

    for (int i = 0; i < nThreads; i++) { 
        Thread t = new Thread() { 
            public void run() { 
                try { 
                    startGate.await(); 
                    try { 
 开发者_开发知识库                       task.run(); 
                    } finally { 
                        endGate.countDown(); 
                    } 
                } catch (InterruptedException ignored) { } 
            } 
        }; 
        t.start(); 
    } 

    long start = System.nanoTime(); 
    startGate.countDown(); 
    endGate.await(); 
    long end = System.nanoTime(); 
    return end-start; 
}} 


You are not wrong. The code will in fact hang. Keep in mind, many of their code examples are written to give the reader and understanding of what the code snippet is supposed to functionally do. They do not intend for developers to use their code out of the box without testing of their own.

For example, someone was asking about creating a self populating cache. Someone pointed to the Memoizer section in JCiP where Tim Peierls followed with:

The Memoizer class presented in that section is only to illustrate a technique. It lacks a number of useful features, and it is nowhere near production-ready.

Use MapMaker anywhere you might have been tempted to use or adapt Memoizer.

http://old.nabble.com/How-to-implement-a-self-populating-memoizer-cache--td30121001.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜