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 ...
随机推荐
- html5中的大纲
html5中的大纲 前言: 在html5中我们可以使用结构元素来编排一份大纲,这样我们就可以通过这个网页的大纲来了解网页中有哪些内容,网页中以什么样的形式来组织这些内容有更清楚的认识. 1.html5 ...
- js-DOM控制HTML
一. dom对象控制html HTML DOM 是 W3C 标准(是 HTML 文档对象模型的英文缩写,Document Object Model for HTML). HTML DOM ...
- 轻松了解Spring中的控制反转和依赖注入(一)
我们回顾一下计算机的发展史,从最初第一台计算机的占地面积达170平方米,重达30吨,到现如今的个人笔记本,事物更加轻量功能却更加丰富,这是事物发展过程中的一个趋势,在技术领域中同样也是如此,企业级Ja ...
- Sprint第三个冲刺(第三天)
一.Sprint介绍 任务进度: 二.Sprint周期 看板: 燃尽图:
- 重新想象 Windows 8.1 Store Apps (80) - 控件增强: WebView 之基本应用, POST 数据, 与 JavaScript 交互
[源码下载] 重新想象 Windows 8.1 Store Apps (80) - 控件增强: WebView 之基本应用, POST 数据, 与 JavaScript 交互 作者:webabcd 介 ...
- Discuz的缓存体系
参考文档:<http://dev.discuz.org/wiki/index.php?title=缓存机制> Discuz中涉及数据缓存的地方有: 1. session Dz的sessio ...
- MyBatis的一些基本操作
在学校里只学过一点点的hibernate基础,但是这几天被熊哥叫去写好几个类的接口,所以就去百度了一下mybatis的接口方式怎么使用.1定义接口,并且定义其中要使用到的方法,这里必须注意到的是方法名 ...
- AC自动机---Searching the String
ZOJ 3228 题目网址:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=16401 Description Little ...
- 每个软件都自己把操作系统的host配置项加到内存中供频繁调用
nginx的转发,http_pass 转发到一个域名passport.ab.cn 那具体是到哪台机器上. 其实可以通过/etc/hosts文件来配置的. 可以理解,这个hosts文件是操作系统级别的, ...
- 【OpenCV & CUDA】OpenCV和Cuda结合编程
一.利用OpenCV中提供的GPU模块 目前,OpenCV中已提供了许多GPU函数,直接使用OpenCV提供的GPU模块,可以完成大部分图像处理的加速操作. 基本使用方法,请参考:http://www ...