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 ...
随机推荐
- Html5+css3+angularjs+jquery+webAPi 开发手机web(一)
前言 随着浏览器的发展 HTML5+CSS3 的使用也越来越广泛,一直想学这个,想学那个折腾下来几乎没学到什么东西.工作经验告诉我,要掌握一门技术,就需要在项目中去磨练, 所以我就准备开发一个手机端的 ...
- ASP.NET Core学习零散记录
赶着潮流听着歌,学着.net玩着Core 竹子学Core,目前主要看老A(http://www.cnblogs.com/artech/)和tom大叔的博客(http://www.cnblogs.com ...
- C#操作IIS程序池及站点的创建配置
最近在做一个WEB程序的安装包:对一些操作IIS进行一个简单的总结:主要包括对IIS进行站点的新建以及新建站点的NET版本的选择,还有针对IIS7程序池的托管模式以及版本的操作:首先要对Microso ...
- MVC显示详细记录Without Entity Framework
看过此篇<MVC用非Entity Framework将数据显示于视图(二)>http://www.cnblogs.com/insus/p/3364482.html 了解到把数据库中数据表的 ...
- java 接口学习
你应该知道接口是一种契约,它与实现方式无关 但是类,即使是抽象类,你都能自定义成员变量,而成员变量往往就与实现方式有关. 这一点的实际意义不大. 但是有一点,类会暴露太多不必要,甚至不能暴露的东西,你 ...
- 具有timeout 功能的函数调用
做项目的时候有时经常会需要一个带有timeout功能的函数调用. 比如从后台读数据并期望在给定时间内返回.借此机会包装了一个简单的C# class, 直接上代码吧. public class Time ...
- 线段树---Atlantis
题目网址:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=110064#problem/A Description There are se ...
- ztree addNode editName removeNode
1.ztree api中完全拥有以上操作的相关解释,及简单Demo. 2.主要是要学会将单独的效果组合起来使用. 2.1 如: 添加完新的Node节点之后,怎么立即进入新节点的编辑状态来修改名称(或 ...
- MyEclipse+Mysql (二)
上一节介绍了如何在Myeclipse中连接mysql 这一节介绍如何在java程序中访问mysql数据库中的数据b并进行简单的操作 创建一个javaProject,并输入如下java代码: packa ...
- 那一夜,我们..奋笔疾书敲出的--->>库存管理系统
说了会再见,最近好吗?无论你在哪里>也许你在温暖的家,或许你在身在异乡的城市;或许你高高的峰顶放生高歌,或许你还在陡峭的山峰半空努力攀爬.......相信我们都会登上顶峰,"会当凌绝顶 ...