Principle

  1. The presence of the synchronized modifier in a method declaration is an implementation detail, not a part of its exported API.
  2. To enable safe concurrent use, a class must clearly document what level of thread safety it supports.

    Immutable

    • immutable —Instances of this class appear constant. No external synchronization is necessary. Examples include String , Long, and BigInteger (Item 15).

    ThreadSafe

    • unconditionally thread-safe —Instances of this class are mutable, but the class has sufficient internal synchronization that its instances can be used concurrently without the need for any external synchronization. Examples include Random and ConcurrentHashMap.

    • conditionally thread-safe —Like unconditionally thread-safe, except that some methods require external synchronization for safe concurrent use. Examples include the collections returned by the Collections.synchronized wrappers, whose iterators require external synchronization.

    Note

    If an object represents a view on some other object, the client generally must synchronize on the backing object, so as to prevent its direct modification. For example, the documentation for Collections.synchronizedMap says this:

    It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views:

    Map<K, V> m = Collections.synchronizedMap(new HashMap<K, V>());

    ...

    Set<K> s = m.keySet(); // Needn't be in synchronized block

    ...

    synchronized(m) { // Synchronizing on m, not s!

    for (K key : s)

    key.f();

    }

    NotThreadSafe

    • not thread-safe—Instances of this class are mutable. To use them concurrently, clients must surround each method invocation (or invocation sequence) with external synchronization of the clients' choosing . Examples include the general-purpose collection implementations, such as ArrayList and HashMap.

    • thread-hostile— This class is not safe for concurrent use even if all method invocations are surrounded by external synchronization. Thread hostility usually results from modifying static data without synchronization. No one writes a thread-hostile class on purpose; such classes result from the failure to consider concurrency. Luckily, there are very few thread-hostile classes or methods in the Java libraries. The System.runFinalizersOnExit method is thread-hostile and has been deprecated.

    The description of a class's thread safety generally belongs in its documentation comment, but methods with special thread safety properties should describe these properties in their own documentation comments.

    It is not necessary to document the immutability of enum types. Unless it is obvious from the return type, static factories must document the thread safety of the returned object, as demonstrated by Collections.synchronizedMap (above).

    Private lock object idiom

  3. preventdenial-of-service attack by avoiding holding publicly accessible lock from the client.
  4. Particularly well-suited to classes designed for inheritance.   

    // Private lock object idiom - thwarts denial-of-service attack

    private final Object lock = new Object();

    public void foo() {

    synchronized(lock) {

    ...

    }

    }

    Summary

    Every class should clearly document its thread safety properties with a carefully worded prose description or a thread safety annotation. The synchronized modifier plays no part in this documentation. Conditionally thread-safe classes must document which method invocation sequences require external synchronization, and which lock to acquire when executing these sequences. If you write an unconditionally thread-safe class, consider using a private lock object in place of synchronized methods. This protects you against synchronization interference by clients and subclasses and gives you the flexibility to adopt a more sophisticated approach to concurrency control in a later release.

Effective Java 70 Document thread safety的更多相关文章

  1. Effective Java 62 Document all exceptions thrown by each method

    Principle Always declare checked exceptions individually, and document precisely the conditions unde ...

  2. Effective Java 73 Avoid thread groups

    Thread groups were originally envisioned as a mechanism for isolating applets for security purposes. ...

  3. Effective Java Index

    Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...

  4. 《Effective Java》读书笔记 - 10.并发

    Chapter 10 Concurrency Item 66: Synchronize access to shared mutable data synchronized这个关键字不仅保证了同步,还 ...

  5. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

  6. 【Effective Java】阅读

    Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...

  7. Java Concurrency In Practice -Chapter 2 Thread Safety

    Writing thread-safe code is managing access to state and in particular to shared, mutable state. Obj ...

  8. Thread Safety in Java(java中的线程安全)

    Thread Safety in Java is a very important topic. Java provide multi-threaded environment support usi ...

  9. Effective Java 44 Write doc comments for all exposed API elements

    Principle You must precede every exported class, interface, constructor, method, and field declarati ...

随机推荐

  1. MySQL安全问题(防范必知)

    对于任何一种数据库来说,安全问题都是非常重要的.如果数据库出现安全漏洞,轻则数据被窃取,重则数据被破坏,这些后果对于一些重要的数据库都是非常严重的.下面来从操作系统和数据库两个层对MySQL的安全问题 ...

  2. 连接不上mysqlworkbench问题解决方法

    连接mysqlworkbench出现如下提示:     查看ip     加入host的范围 mysql> select user,host from mysql.user;+--------- ...

  3. 适用于jquery1.11.1的ajaxfileupload.js

    ajaxfileupload源码 解决上传成功不走success的问题 解决高版本jquery兼容性问题 jQuery.extend({ createUploadIframe: function(id ...

  4. 整理的有用的一些EF的CommonDAL小封装

    CommonDAL封装: using System; using System.Collections.Generic; using System.Data.Entity; using System. ...

  5. WPF,给颜色SolidColorBrush添加动画

    /// <summary> /// 设置颜色动画 /// </summary> /// <returns></returns> private Soli ...

  6. JSChart_页面图形报表

    首先在页头的"head"中加上: $(document).ready(function() { //myData与colors变量  是做演示用的,可以直接赋值给myChart就可 ...

  7. jdbcTemplate queryForObject 查询 结果集 数量

    1.组织sql语句, 查询参数 数组, 设置返回类型 public int countByCondtion(String title, int mediaType, String currentSta ...

  8. 两种设计模式(1)==>>“简单工厂”

    我们以做一个计算器为例,给大家介绍简单工厂的应用: 效果: 这里我们使用 继承 ,虚方法, 简单工厂的设计模式来完成 首先,我们除了搭好窗体外,我们应该把我们的一些类准备好: 1.计算的父类Calcu ...

  9. html格式化

    解决方法是: 在myeclipse中是这样解决的: 点击 myeclipse菜单栏的 window选项卡,找到下拉 perferences 选项 , 在里面快捷 "搜索" 框里面输 ...

  10. 静态导入Static import

    静态导入Static import 要使用静态成员(方法和变量)我们必须给出提供这个静态成员的类. 使用静态导入可以使被导入类的静态变量和静态方法在当前类直接可见,使用这些静态成员无需再给出他们的类名 ...