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 ...
随机推荐
- Tools Function
public static void TraceLog(string message, string logFileName) { string tmppath = AppDomain.Current ...
- BlocksKit初见:一个支持将delegate转换成block的Cocoa库
简介 项目主页: https://github.com/zwaldowski/BlocksKit BlocksKit 是一个开源的框架,对 Cocoa 进行了扩展,将许多需要通过 delegate 调 ...
- 用cryptico.js实现RSA加密(应对cryptico不支持PEM)
问题: 随手分享一下好了,这个问题困扰了很久. cryptico.js这个加密算法库很全,很适合在前端用到各种加密解密算法的需求.但是美中不足的是,它的RSA加密不支持PEM格式,所以如果你后端用ja ...
- JavaScript基础概念
1.JavaScript在浏览器中是解释执行的: 2.JavaScript是一中弱类型的语言,在使用变量前,可以不用先申明: 3.JavaScript使用了对象对象程序设计思想: 4.JavaScri ...
- linq之let子句
在Linq查询中Let子句可以创建一个新的范围变量,并使用该变量保存表达式的结果. 看下面的例子: private void LetQuery() { List<UserBaseInfo> ...
- Azure开发者任务之三:理解Azure应用程序(上)
作为Windows Azure的托管服务被设计和开发的应用程序由这两部分组成: 1,托管代码 2,XML配置文件 托管代码对应不同的角色 XML文件对应不同的配置设置 我们可以看一下下面这张图,它详细 ...
- 重新想象 Windows 8.1 Store Apps (74) - 新增控件: Flyout, MenuFlyout, SettingsFlyout
[源码下载] 重新想象 Windows 8.1 Store Apps (74) - 新增控件: Flyout, MenuFlyout, SettingsFlyout 作者:webabcd 介绍重新想象 ...
- 互联网产品团队中Web前端工程师的重要性
国内外各大互联网公司,都有UEx/d|UCD|CDC(Customer Research & User Experience Design Center)团队. 在很多公司会认为,合格的产品经 ...
- TCMalloc优化MySQL、Nginx内存管理
TCMalloc的全称为Thread-Caching Malloc,是谷歌开发的开源工具google-perftools中的一个成员. 与标准的glibc库的Malloc相比,TCMalloc库在内存 ...
- 「C语言」int main还是void main?
从大一入学刚接触C到现在已满7个月了,虽然刚开始就知道```int main```才是标准的写法,但一直没有深刻理解为什么不能用```void main```而必须使用```int main```. ...