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. [linux]执行pip安装的程序:command not found

    执行pip安装的程序:command not found 问题描述: 我有一台阿里云服务器,上面装的是centos系统,我用pip安装好vituralenv,都没办法直接启动.同样 我今天在部署我的t ...

  2. JAVA jdbc(数据库连接池)学习笔记(一)

    学习内容: 1.JDBC的含义... JDBC想必学过JAVA的就不会陌生,JDBC到底是什么呢?其实就是由JAVA的一些类和接口构成的API,保存在java.sql和javax.sql..包中的一些 ...

  3. LVS使用整理(1)

    开始安装LVS 1)下载相关软件包 mkdir -p /home/tools/cd /home/tools/wget http://www.linuxvirtualserver.org/softwar ...

  4. HTTP请求响应报文&&相关状态码&&GET_POST请求方法 总结

    HTTP请求报文: 一个HTTP请求报文由四个部分组成:请求行.请求头部.空行.请求数据 1.请求行   请求行由请求方法字段.URL字段和HTTP协议版本字段3个字段组成,它们用空格分隔.比如 GE ...

  5. UnityShader快速上手指南(四)

    简介 由于其他项目中断了几天更新,继续~~ 这一篇主要是讲光照的(包含漫反射和高光以及多光源的处理) 还是先来看看具体效果(多光源后面单独展示) 有了基本的光照处理之后越来越有立体感了有不有 ╮(╯▽ ...

  6. c++容器(vector、list、deque)

    vector ,deque 和 list 顺序性容器: 向量 vector :   是一个线性顺序结构.相当于数组,但其大小可以不预先指定,并且自动扩展.它可以像数组一样被操作,由于它的特性我们完全可 ...

  7. jquery实现下拉框功能

    说不清楚,直接上图 <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtm ...

  8. macbook 我们需要买吗

    能否写出好代码与是否使用“好”的电脑是没有直接关系的.

  9. idea使用maven搭建springmvc

    最近学着搭建springmvc,写此博客记录一下 idea版本:2016.3.1maven: apache-maven-3.3.9tomcat:apache-tomcat-8.5.8 1.New Pr ...

  10. 再谈visibility:hidden和display:none

    之前写过一篇有关visibility:hidden和display:none的文章:为什么要用用visibility:hidden;代替display:none;?主要是从浏览器性能方面入手,却没写两 ...