Effective Java 70 Document thread safety
Principle
- The presence of the synchronized modifier in a method declaration is an implementation detail, not a part of its exported API.
- 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
- preventdenial-of-service attack by avoiding holding publicly accessible lock from the client.
- 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的更多相关文章
- Effective Java 62 Document all exceptions thrown by each method
Principle Always declare checked exceptions individually, and document precisely the conditions unde ...
- Effective Java 73 Avoid thread groups
Thread groups were originally envisioned as a mechanism for isolating applets for security purposes. ...
- 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 ...
- 《Effective Java》读书笔记 - 10.并发
Chapter 10 Concurrency Item 66: Synchronize access to shared mutable data synchronized这个关键字不仅保证了同步,还 ...
- Effective Java 目录
<Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...
- 【Effective Java】阅读
Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...
- 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 ...
- Thread Safety in Java(java中的线程安全)
Thread Safety in Java is a very important topic. Java provide multi-threaded environment support usi ...
- Effective Java 44 Write doc comments for all exposed API elements
Principle You must precede every exported class, interface, constructor, method, and field declarati ...
随机推荐
- 开放产品开发(OPD):OPD框架
在 开放产品开发(OPD):开篇 中讲了一下OPD是什么,以及它主要指引的方法,这篇文字将给大家介绍一下OPD框架. 一个公司有三种经营模式,像游戏代理的属于运营型,做企业定制项目管理软件的属于项目型 ...
- Android 学习笔记之使用多线程实现断点下载...
PS:莫名其妙的迷茫... 学习内容: 1.使用多线程实现文件下载... 多线程下载是加快下载速度的一种方式..通过开启多个线程去执行一个任务..可以使任务的执行速度变快..多线程的任务下载时常都 ...
- 2015百度之星 IP聚合
IP聚合 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others) Problem Descri ...
- Linq专题之对象初始化器
在C#3.0之前,如果创建一个新的对象,往往需要调用类的构造函数来初始化该对象的值,在c#3.0提供了一个"对象初始化器"的机制,使得开发人员在创建新的对象时不通过调用类的构造函数 ...
- C#设计模式——抽象工厂模式(Abstract Factory Pattern)
一.概述在软件开发中,常常会需要创建一系列相互依赖的对象,同时,由于需求的变化,往往存在较多系列对象的创建工作.如果采用常规的创建方法(new),会造成客户程序和对象创建工作的紧耦合.对此,抽象工厂模 ...
- 用于dbnull的数据转换。因为用convert.to无法转换dbnull类型
/// <summary> /// add by wolf /// </summary> public static class ExtendObject { public s ...
- php中的字符串常用函数(一) strpos() 子字符首次出现的位置
strpos($str, $needle); 1.返回$needle在$str首次出现的位置.(大小写敏感). 2.从php5开始$needle支持多字符.php4只能用单个字符. 3.能找到$nee ...
- 常用 Git 命令清单(摘录)
来源:阮一峰的网络日志 网址:http://www.ruanyifeng.com/blog/2015/12/git-cheat-sheet.html 我每天使用 Git ,但是很多命令记不住. 一般来 ...
- mysql命令行备份数据库
MySQL数据库使用命令行备份|MySQL数据库备份命令 例如: 数据库地址:127.0.0.1 数据库用户名:root 数据库密码:pass 数据库名称:myweb 备份数据库到D盘跟目录 mysq ...
- IOS6学习笔记(三)
1.ARC空声明变量 使用ARC的另一个优势是所有未初始化的变量默认都是“空值化”的.这意味着像下面这样的声明使用ARC编译后指向的是空值(nil): NSObject *myObject1,*myO ...