Effective Java 66 Synchronize access to shared mutable data
synchronized - Only a single thread can execute a method or block at one time.
Not only does synchronization prevent a thread from observing an object in an inconsistent state, but it ensures that each thread entering a synchronized method or block sees the effects of all previous modifications that were guarded by the same lock.
Synchronization is required for reliable communication between threads as well as for mutual exclusion.
Principles
Do not use Thread.stop.
Synchronization has no effect unless both read and write operations are synchronized.
/**
* Demo for 66 Synchronize access to shared mutable data.
*/
package com.effectivejava.concurrency;
import java.util.concurrent.TimeUnit;
/**
* Properly synchronized cooperative thread termination
* @author Kaibo
*
*/
public class StopThread {
private static boolean stopRequested;
private static synchronized void requestStop() {
stopRequested = true;
System.out.println("request stop from another thread.");
}
private static synchronized boolean stopRequested() {
return stopRequested;
}
public static void main(String[] args) throws InterruptedException {
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
int i = 0;
while (!stopRequested())
System.out.println(i++);
}
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
requestStop();
}
}
/**
* Cooperative thread termination with a volatile field
*
* @author Kaibo
*
*/
public class StopThreadWithVolatile {
private static volatile boolean stopRequested;
public static void main(String[] args) throws InterruptedException {
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
int i = 0;
while (!stopRequested)
System.out.println(i++);
}
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
stopRequested = true;
}
}
NOTE
operator(++) is not atomic - If a second thread reads the field between the time a thread reads the old value and writes back a new one, the second thread will see the same value as the first and return the same serial number.
// Broken - requires synchronization!
private static volatile int nextSerialNumber = 0;
public static int generateSerialNumber() {
return nextSerialNumber++;
}
// Correct way
private static final Atomic Long nextSerialNum = new AtomicLong();
public static long generateSerialNumber() {
return nextSerialNum.getAndIncrement();
}
4. Confine mutable data to a single thread
Summary
When multiple threads share mutable data, each thread that reads or writes the data must perform synchronization. Without synchronization, there is no guarantee that one thread’s changes will be visible to another. The penalties for failing to synchronize shared mutable data are liveness and safety failures. If you need only inter-thread communication, and not mutual exclusion, the volatile modifier is an acceptable form of synchronization, but it can be tricky to use correctly.
Effective Java 66 Synchronize access to shared mutable data的更多相关文章
- 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】阅读
Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...
- Effective Java 目录
<Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...
- Effective Java 67 Avoid excessive synchronization
Principle To avoid liveness and safety failures, never cede control to the client within a synchroni ...
- Effective Java 第三版——8. 避免使用Finalizer和Cleaner机制
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
- Effective Java 第三版——13. 谨慎地重写 clone 方法
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
- Effective Java
Effective Java 创建和销毁对象---考虑用静态工厂方法代替构造器 构造器是创建一个对象实例最基本也最通用的方法,大部分开发者在使用某个class的时候,首先需要考虑的就是如何构造和初始化 ...
- Effective Java 15 Minimize mutability
Use immutable classes as much as possible instead of mutable classes. Advantage Easy to design, impl ...
随机推荐
- Java魔法堂:注解用法详解——@SuppressWarnings
一.前言 编码时我们总会发现如下变量未被使用的警告提示: 上述代码编译通过且可以运行,但每行前面的“感叹号”就严重阻碍了我们判断该行是否设置的断点了.这时我们可以在方法前添加 @SuppressWar ...
- IOS开发UI基础UIControl事件
UIControl事件1.UIControlEventTouchDown单点触摸按下事件:用户点触屏幕,或者又有新手指落下的时候. 2.UIControlEventTouchDownRepeat多点触 ...
- 利用session做国际化引起的old区内存爆满及修复方法
题记:昨天加班打车回家,看见前面有辆路虎在高速上开的巨慢,挡住了我坐的出租车的路,于是就跟司机吐槽了一句:“前面这车怎么这么面啊?”,司机沉默了大概3秒,说了一句富含哲理性的话:“没有面车,只有面人” ...
- 6/14 sprint2 看板和燃尽图的更新
看板: 燃尽图: 例会照: 总结:因为最近刚好碰上端午假期,再加上程序出了点问题,所以导致进度有点慢, 但是我们还是很努力地在找资料把问题给解决了,虽然完成的情况有点不如人意, 但是我们付出的努力还是 ...
- C#设计模式——观察者模式(Observer Pattern)
一.概述在软件设计工作中会存在对象之间的依赖关系,当某一对象发生变化时,所有依赖它的对象都需要得到通知.如果设计的不好,很容易造成对象之间的耦合度太高,难以应对变化.使用观察者模式可以降低对象之间的依 ...
- js获取浏览器当前窗口的高度长度
js获取浏览器可见区域(不包括标题栏.地址栏.收藏夹栏状态栏等额外区域,仅为页面呈现区域)的高度和宽度宽度:document.documentElement.clientWidth高度:documen ...
- sencha panel的头header上添加刷新按钮
var plet3=Ext.create('portaltest3.view.Portlet', { title: '提醒', ...
- csharp: Domain-Driven Design(领域驱动设计)
http://dddsample.sourceforge.net/ https://github.com/citerus/dddsample-core http://dddsamplenet.code ...
- [PE结构分析] 10.基址重定位
源代码如下: typedef struct _IMAGE_BASE_RELOCATION { DWORD VirtualAddress; DWORD SizeOfBlock; // WORD Type ...
- 平衡二叉树---Shaolin
Description Shaolin temple is very famous for its Kongfu monks.A lot of young men go to Shaolin temp ...