Principle

  1. To avoid liveness and safety failures, never cede control to the client within a synchronized method or block.
  2. Do as little work as possible inside synchronized regions.
  3. You should make a mutable class thread-safe (Item 70) if it is intended for concurrent use and you can achieve significantly higher concurrency by synchronizing internally than you could by locking the entire object externally. Otherwise, don't synchronize internally. Let the client synchronize externally where it is appropriate. (eg. StringBuffer vs. StringBuilder)
  4. If a method modifies a static field, you must synchronize access to this field, even if the method is typically used only by a single thread.

The failure by invoking alien method

/**

* Demo for "67 Avoid excessive synchronization".

*/

package com.effectivejava.concurrency;

import java.util.ArrayList;

import java.util.Collection;

import java.util.HashSet;

import java.util.List;

import java.util.Set;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import com.effectivejava.classinterface.ForwardingSet;

/**

* @author Kaibo Hao

*

*/

public class ObservableSet<E> extends ForwardingSet<E> {

/**

* @param s

*/

public ObservableSet(Set<E> s) {

super(s);

}

private final List<SetObserver<E>> observers = new ArrayList<SetObserver<E>>();

public void addObserver(SetObserver<E> observer) {

synchronized (observers) {

observers.add(observer);

}

}

public boolean removeObserver(SetObserver<E> observer) {

synchronized (observers) {

return observers.remove(observer);

}

}

private void notifyElementAdded(E element) {

synchronized (observers) {

for (SetObserver<E> observer : observers)

// calling the alien method

observer.added(this, element);

}

}

@Override

public boolean add(E element) {

boolean added = super.add(element);

if (added)

notifyElementAdded(element);

return added;

}

@Override

public boolean addAll(Collection<? extends E> c) {

boolean result = false;

for (E element : c)

result |= add(element); // calls notifyElementAdded

return result;

}

public static void main(String[] args) {

ObservableSet<Integer> set =

new ObservableSet<Integer>(new HashSet<Integer>());

set.addObserver(new SetObserver<Integer>() {

public void added(ObservableSet<Integer> s, Integer e) {

System.out.println(e);

}

});

for (int i = 0; i < 100; i++)

set.add(i);

}

}

Case 1: Failed to remove an element from a list in the midst of iterating over it, which is illegal.

Root Cause - The iteration in the notifyElementAdded method is in a synchronized block to prevent concurrent modification, but it doesn't prevent the iterating thread itself from calling back into the observable set and modifying its observers list.

// Removing the Observer during the iteration.

set.addObserver(new SetObserver<Integer>() {

public void added(ObservableSet<Integer> s, Integer e) {

System.out.println(e);

if (e == 23) s.removeObserver(this);

}

});

Case 2: Failed to background thread for removing.

Root Cause: - The object in the synchronized region are locked by the main thread which cannot be modified by the background thread.

// Observer that uses a background thread needlessly

set.addObserver(new SetObserver<Integer>() {

@Override

public void added(final ObservableSet<Integer> s, Integer e) {

System.out.println(e);

if (e == 23) {

ExecutorService executor = Executors

.newSingleThreadExecutor();

final SetObserver<Integer> observer = this;

try {

executor.submit(new Runnable() {

@Override

public void run() {

s.removeObserver(observer);

}

}).get();

} catch (ExecutionException ex) {

throw new AssertionError(ex.getCause());

} catch (InterruptedException ex) {

throw new AssertionError(ex.getCause());

} finally {

executor.shutdown();

}

}

}

});

Reentrant lock : Locks in Java programming language are reentrant, in other words such calls above won't deadlock.

Solution 1 - Taking snapshot and move Alien method outside of synchronized block - open calls

private void notifyElementAdded(E element) {

List<SetObserver<E>> snapshot = null;

synchronized(observers) {

snapshot = new ArrayList<SetObserver<E>>(observers);

}

for (SetObserver<E> observer : snapshot)

observer.added(this, element);

}

Solution 2(Prefered) - Thread-safe observable set with CopyOnWriteArrayList

// Thread-safe observable set with CopyOnWriteArrayList

private final List<SetObserver<E>> observers = new CopyOnWriteArrayList<SetObserver<E>>();

public void addObserver(SetObserver<E> observer) {

observers.add(observer);

}

public boolean removeObserver(SetObserver<E> observer) {

return observers.remove(observer);

}

private void notifyElementAdded(E element) {

for (SetObserver<E> observer : observers)

observer.added(this, element);

}

CopyOnWriteArrayList

It is a variant of ArrayList in which all write operations are implemented by making a fresh copy of the entire underlying array. Performance may be atrocious, but it's perfect for observer lists which are rarely modified and often traversed.

Note

In a multicore world, the real cost of excessive synchronization is not the CPU time spent obtaining locks; it is the lost opportunities for parallelism and the delays imposed by the need to ensure that every core has a consistent view of memory.

If you do synchronize your class internally, you can use various techniques to achieve high concurrency, such as lock splitting, lock striping, and nonblocking concurrency control.

Summary

To avoid deadlock and data corruption, never call an alien method from within a synchronized region. More generally, try to limit the amount of work that you do from within synchronized regions. When you are designing a mutable class, think about whether it should do its own synchronization. In the modern multicore era, it is more important than ever not to synchronize excessively. Synchronize your class internally only if there is a good reason to do so, and document your decision clearly (Item 70).

Effective Java 67 Avoid excessive synchronization的更多相关文章

  1. Effective Java 07 Avoid finallizers

    NOTE Never do anything time-critical in a finalizer. Never depend on a finalizer to update critical ...

  2. Effective Java 50 Avoid strings where other types are more appropriate

    Principle Strings are poor substitutes for other value types. Such as int, float or BigInteger. Stri ...

  3. Effective Java 59 Avoid unnecessary use of checked exceptions

    The burden is justified if the exceptional condition cannot be prevented by proper use of the API an ...

  4. Effective Java 73 Avoid thread groups

    Thread groups were originally envisioned as a mechanism for isolating applets for security purposes. ...

  5. Effective Java 05 Avoid creating unnecessary objects

    String s = new String("stringette"); // Don't do this. This will create an object each tim ...

  6. Effective Java 48 Avoid float and double if exact answers are required

    Reason The float and double types are particularly ill-suited for monetary calculations because it i ...

  7. 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 ...

  8. 《Effective Java》读书笔记 - 10.并发

    Chapter 10 Concurrency Item 66: Synchronize access to shared mutable data synchronized这个关键字不仅保证了同步,还 ...

  9. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

随机推荐

  1. 一秒钟生成自己的iOS客户端

    原谅我这个标题党 想当年我也是亲自学过几天Objective-c的程序猿,我一眼就知道我是在骗人,但那有怎样呢!还不是满大街都是各种<十分钟让你明白Objective-C的语法>.< ...

  2. ActiveMQ学习(二)——MQ的工作原理

    如图所示 首先来看本地通讯的情况,应用程序A和应用程序B运行于同一系统A,它们之间可以借助消息队列技术进行彼此的通讯:应用程序A向队列1发送一条信息,而当应用程序B需要时就可以得到该信息. 其次是远程 ...

  3. scrum1.4---Sprint 计划

    燃尽图

  4. 2014 Asia AnShan Regional Contest --- HDU 5073 Galaxy

    Galaxy Problem's Link:   http://acm.hdu.edu.cn/showproblem.php?pid=5073 Mean: 在一条数轴上,有n颗卫星,现在你可以改变k颗 ...

  5. BI之SSAS完整实战教程7 -- 设计维度、细化维度中 :浏览维度,细化维度

    上篇文章我们已经将Dim Geography维度设计好. 若要查看维度的成员, AS需要接收该维度的详细信息(包括已创建的特性.成员属性以及多级层次结构), 通过XMLA与AS的实例进行通信. 今天我 ...

  6. Unity3D脚本语言UnityScript初探

    译者注: Unity3D中支持三种语言:JavaScript.C#.Boo,很多人不知道如何选择,通过这篇译文,我们可以搞清楚这三者语言的来龙去脉,对选择主语言有一定的借鉴意义. 首先,Unity是基 ...

  7. JDK动态代理的实现及原理

    Proxy.newProxyInstance(classloader,Class,invocationHandler) 调用getProxyClass0(loader, interfaces)生成代理 ...

  8. [moka同学收藏]Yii2.0 rules验证规则

    required : 必须值验证属性 [['字段名'],required,'requiredValue'=>'必填值','message'=>'提示信息']; #说明:CRequiredV ...

  9. ASP.NET Web API通过ActionFilter来实现缓存

    using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Sys ...

  10. IIS在默认情况并不支持对PUT和DELETE请求的支持

    IIS在默认情况并不支持对PUT和DELETE请求的支持: IIS拒绝PUT和DELETE请求是由默认注册的一个名为:“WebDAVModule”的自定义HttpModule导致的.WebDAV的全称 ...