`
leonzhx
  • 浏览: 793979 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Item 69: Prefer concurrency utilities to wait and notify

阅读更多

1.  Given the difficulty of using wait and notify correctly, you should use the higher-level concurrency utilities instead. The higher-level utilities in java.util.concurrent fall into three categories: the Executor Framework, concurrent collections and synchronizers.

 

2.  The concurrent collections provide high-performance concurrent implementations of standard collection interfaces such as List, Queue, and Map. To provide high concurrency, these implementations manage their own synchronization internally. Therefore, it is impossible to exclude concurrent activity from a concurrent collection; locking it will have no effect but to slow the program.

 

3.  ConcurrentMap extends Map and adds several methods, including putIfAbsent(key, value), which inserts a mapping for a key if none was present and returns the previous value associated with the key, or null if there was none. This makes it easy to implement thread-safe canonicalizing maps.

 

4.  Some of the collection interfaces have been extended with blocking operations, which wait (or block) until they can be successfully performed. BlockingQueue extends Queue and adds several methods, including take, which removes and returns the head element from the queue, waiting if the queue is empty. This allows blocking queues to be used for work queues (also known as producer-consumer queues), to which one or more producer threads enqueue work items and from which one or more consumer threads dequeue and process items as they become available. As you’d expect, most ExecutorService implementations, including ThreadPoolExecutor, use a BlockingQueue.

 

5.  Countdown latches are single-use barriers that allow one or more threads to wait for one or more other threads to do something. The sole constructor for CountDownLatch takes an int that is the number of times the countDown method must be invoked on the latch before all waiting threads are allowed to proceed.

 

6.  For interval timing, always use System.nanoTime in preference to System.currentTimeMillis. System.nanoTime is both more accurate and more precise, and it is not affected by adjustments to the system’s real-time clock.

 

7.  The wait method is used to make a thread wait for some condition. It must be invoked inside a synchronized region that locks the object on which it is invoked. Here is the standard idiom for using the wait method:

// The standard idiom for using the wait method
synchronized (obj) {
    while (<condition does not hold>)
        obj.wait(); // (Releases lock, and reacquires on wakeup)
    // Perform action appropriate to condition
}

 

8.  Always use the wait loop idiom to invoke the wait method; never invoke it outside of a loop. The loop serves to test the condition before and after waiting. Testing the condition before waiting and skipping the wait if the condition already holds are necessary to ensure liveness. If the condition already holds and the notify (or notifyAll) method has already been invoked before a thread waits, there is no guarantee that the thread will ever wake from the wait. Testing the condition after waiting and waiting again if the condition does not hold are necessary to ensure safety. If the thread proceeds with the action when the condition does not hold, it can destroy the invariant guarded by the lock.

 

9.  There are several reasons a thread might wake up when the condition does not hold:

    1)  Another thread could have obtained the lock and changed the guarded state between the time a thread invoked notify and the time the waiting thread woke.

    2)  Another thread could have invoked notify accidentally or maliciously when the condition did not hold. 

    3)  The notifying thread could be overly “generous” in waking waiting threads.

    4)  The waiting thread could (rarely) wake up in the absence of a notify. This is known as a spurious wakeup.

 

10.  The notifyAll method should generally be used in preference to notify. Because it guarantees that you’ll wake the threads that need to be awakened.

 

11.  As an optimization, you may choose to invoke notify instead of notifyAll if all threads that could be in the wait-set are waiting for the same condition and only one thread at a time can benefit from the condition becoming true. Even if these conditions appear true, there may be cause to use notifyAll in place of notify. Because using notifyAll in place of notify protects against accidental or malicious waits by an unrelated thread. Such waits could otherwise “swallow” a critical notification, leaving its intended recipient waiting indefinitely.

 

分享到:
评论

相关推荐

    Effective Java 3rd edition(Effective Java第三版英文原版)附第二版

    Item 81: Prefer concurrency utilities to wait and notify Item 82: Document thread safety Item 83: Use lazy initialization judiciously Item 84: Don’t depend on the thread scheduler 12 Serialization ...

    专享:prefer的用法__(全).pdf

    3. 问句“Would you prefer to wait?”询问对方是否愿意等待,回答者表示:“Yes, I’d prefer to.”他更愿意等待。 4. “I prefer my coffee black.”表示说话者喜欢不加奶的咖啡。 5. “I prefer the chair in ...

    Effective C#

    **Item 22: Prefer Defining and Implementing Interfaces to Inheritance** - **Reasons:** Interfaces promote loose coupling and make it easier to swap implementations. - **Implementation:** ```csharp ...

    Copy Constructors and Assignment Operators终极解释

    在编写自定义的复制构造函数和赋值运算符时,还需要遵循一些最佳实践,如"拷贝-and-swap"策略(Copy-and-Swap Idiom)。这个策略在赋值运算符中先创建一个临时对象,然后交换这个临时对象和当前对象的成员,这样可以...

    新人教九年级英语unit单词讲解PPT课件.pptx

    4. **特定情况**:`prefer to do sth.` 用于强调在特定情境下,更愿意做某事,例如:"I prefer to walk."(我宁愿走路。) 5. **对比形式**:`prefer doing sth. to doing sth.` 这种结构表示在两个动作之间,更...

    effective c++

    2. **Item 7: Prefer Initialization to Assignment** - **核心观点**:提倡初始化而非赋值,尤其是在构造函数和成员变量的初始化过程中。 - **应用场景**:适用于对象创建时的资源管理,有助于减少内存泄漏和提高...

    ARM Trace Including: ETM, ETB and Serial Wire Viewer, JTAG and SWD

     How we talk to your CPU using JTAG or SWD.  Trace. ETM™, ETB and SWV. How are they different ?  Triggers, filters and stuff…..  Instrumentation. DCC and ITM.  Breakpoints and Watchpoints ...

    安徽省太和县北城中心学校九年级英语全册Unit9IlikemusicthatIcandancetoSectionA1a_2d导学

    3. prefer sth to sth,如:I prefer fish to meat. 或 I prefer reading to playing. 通过以上内容的学习,学生应能理解并运用这些词汇和语法结构,进行关于音乐喜好的交流,同时也能理解和使用定语从句,提升英语...

    九年级英语下册 Unit 6 Topic1 ABCD学案(无答案) 仁爱版

    - 宁愿…也不…:prefer…to… - 儿童节目:children's program - 新闻报道:news report - 体育节目:sports program - 教育节目:educational program - 娱乐节目:entertainment program - 爱上…:fall ...

    高考英语重点词组固定搭配大全.docx

    此外,还有一些不常接动名词但接不定式的动词,如:aim to do sth., fail to do sth., long to do sth., happen to do sth., hesitate to do sth., struggle to do sth. 二、接不定式作宾补的动词: 1. advise sb....

    ESLint 规则文件

    ESLint是针对javascript代码的静态检查工具。资源是本人配置的ESLint 规则文件。官方文档:http://eslint.org/docs/rules/。

    Ericsson-LTE L12 Radio Network Functionality

    - - **Priority-Based Cell Reselection**: Discusses how UEs can be directed to prefer certain frequencies or PLMNs based on network policies. - - **Speed-Dependent Scaling of Cell Reselection**: ...

    英语词汇固定搭配.doc

    - 宁愿某人做某事,例如:I prefer you to come early rather than late. 28. request sb. to do sth. - 要求某人做某事,例如:The client requested a meeting to discuss the project. 29. remind sb. to do sth...

    Unit6 Good Manners语言点教案示例四 人教版.doc

    - "prefer doing A to doing B"或"prefer to do A rather than do B"都表示宁愿做A而不愿做B。例如:"I prefer working to sitting all day." 这里表达了更倾向于工作的态度。 - "prefer sb. to do sth."表示希望...

    2013年九年级英语下册 Module 8 On the town动词不定式专项练习 外研版

    13. The sitting-room needs to be cleaned, but it’ll have to wait until Saturday. 答案:B. to be cleaned 解析:"sth. need to be done" 表示某事需要被做,need后面接动词不定式的被动形式。 14. The first ...

    动词todo与doing的用法区别.doc

    - **prefer** (宁愿):*I prefer you to stay here.*(我宁愿你留在这里。) - **request** (要求):*He requested her to attend the meeting.*(他要求她参加会议。) - **remind** (提醒):*She reminded me to ...

    tcping查看端口及IP链路情况

    -w 0.5 : for instance, wait 0.5 seconds for a response -d : include date and time on each line -b 1 : enable beeps (1 for on-down, 2 for on-up, 3 for on-change, 4 for always) -r 5 : for instance,...

Global site tag (gtag.js) - Google Analytics