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. fcitx 无法启动

    困扰了好久的问题,终于解决了. 问题描述: 在fcitx的输入法配置栏里,输入法列表是空的,使用Ctrl+space无法启用任何的输入法, 当然此截图中的是有的,这是问题已经解决后的状态了. 解决方法 ...

  2. [转]AutoResetEvent 与 ManualResetEvent区别

    在C#多线程编程中,这两个类几乎是不可或缺的,他们的用法/声明都很类似,那么区别在哪里了? Set方法将信号置为发送状态 Reset方法将信号置为不发送状态 WaitOne等待信号的发送 其实,从名字 ...

  3. Java魔法堂:String.format详解

      目录     一.前言    二.重载方法     三.占位符     四.对字符.字符串进行格式化     五.对整数进行格式化     六.对浮点数进行格式化     七.对日期时间进行格式化 ...

  4. .Net魔法堂:史上最全的ActiveX开发教程——发布篇

    一. 前言 接着上一篇<.Net魔法堂:史上最全的ActiveX开发教程——开发篇>,本篇讲述如何发布我们的ActiveX. 二.废话少讲,马上看步骤! 1. 打包  C#开发的Activ ...

  5. 阅读《构建之法》P384~391

    通过阅读<构建之法>P384~391以及参考阅读杜老师给出的链接,得出一个重要的结论:软件工程师的职业道德至关重要. 软件工程的动态性和需求的前后关系,要求一个规范能对出现的新情形有较强的 ...

  6. struts.custom.i18n.resources国际化

    每种框价都会有国际化的支持,struts2的国际化大致上分为页面的国际化,Action的国际化以及xml的国际化 首先在struts.properties文件中加入以下内容:struts.custom ...

  7. C#客户端Redis服务器的分布式缓存

    介绍 在这篇文章中,我想介绍我知道的一种最紧凑的安装和配置Redis服务器的方式.另外,我想简短地概述一下在.NET / C#客户端下Redis hash(哈希类型)和list(链表)的使用. 在这篇 ...

  8. JS对象的创建与使用

    本文内容:     1.介绍对象的两种类型:     2.创建对象并添加成员:     3.访问对象属性:     4.利用for循环枚举对象的属性类型:     5.利用关键字delete删除对象成 ...

  9. Oracle基础 各种语句的定义格式

    Oracle内建数据类型 一. 字符数据 1. char(size) 2. varchar2(size) 最常用,最大长度4000字节 3. nvhar(size).nvarchar(size) 4. ...

  10. C#的Raw Socket实现网络封包监视

    同Winsock1相比,Winsock2最明显的就是支持了Raw Socket套接字类型,使用Raw Socket,可把网卡设置成混杂模式,在这种模式下,我们可以收到网络上的IP包,当然包括目的不是本 ...