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 ...
随机推荐
- ExtJs创建环境搭建
开发工具Eclipse/MyEclipse. 工具下载:http://pan.baidu.com/s/1sjmiFMH(提供spket和sdk.jsb3, extjs-4.1.1需自己下载) 1. ...
- SQL Server 2016里TempDb的提升
几个星期前,SQL Server 2016的最新CTP版本已经发布了:CTP 2.4(目前已经是CTP 3.0).这个预览版相比以前的CTP包含了很多不同的提升.在这篇文章里我会谈下对于SQL Ser ...
- SQL Server中的事务日志管理(1/9):事务日志概况
当一切正常时,没有必要特别留意什么是事务日志,它是如何工作的.你只要确保每个数据库都有正确的备份.当出现问题时,事务日志的理解对于采取修正操作是重要的,尤其在需要紧急恢复数据库到指定点时.这系列文章会 ...
- 关于SQL SERVER高并发解决方案
现在大家都比较关心的问题就是在多用户高并发的情况下,如何开发系统,这对我们程序员来说,确实是值得研究,最近找工作面试时也经常被问到,其实我早有去关心和了解这类问题,但一直没有总结一下,导致面试时无法很 ...
- [ShortCut] Visual Studio快捷键
msdn官方快捷键说明:https://msdn.microsoft.com/zh-cn/library/da5kh0wa.aspx 测试工具: visual studio 2013 操作步骤: 1. ...
- ADO.NET 基础
*程序要和数据库交互要通过ADO.NET进行,通过ADO.NET就能在程序中执行SQL了,ADO.NET中提供了对各种不同数据库的统一操作接口. 1.连接SQLServer 连接字符串,程序通过链接字 ...
- 区间合并 --- Codeforces 558D : Gess Your Way Out ! II
D. Guess Your Way Out! II Problem's Link: http://codeforces.com/problemset/problem/558/D Mean: 一棵满二叉 ...
- 在Winform开发框架中实现对数据库的加密支持
在很多情况下,我们需要对数据库进行加密,特别是Access数据库.Sqlite数据库,这些直接部署在客户端的数据,因为数据也是客户的资产,数据库总是存在很多相关的秘密或者重要的业务数据,所以一般来说, ...
- node.js实现CURL功能
PHP中的CURL功能很好实现,直接四五行代码封装一下就OK了.node.js中如何实现CURL的功能呢,下面详细介绍. 这里需要用到request这个库,所以先安装此包: npm install r ...
- MVC 5 + EF6 入门完整教程14 -- 动态生成面包屑导航
上篇文章我们完成了 动态生成多级菜单 这个实用组件. 本篇文章我们要开发另一个实用组件:面包屑导航. 面包屑导航(BreadcrumbNavigation)这个概念来自童话故事"汉赛尔和格莱 ...