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 ...
随机推荐
- 资料下载:敏捷个人的成长思考.pptx(第1次线下活动2011.04)
本文挪至 http://www.zhoujingen.cn/blog/629.html PDF下载地址:http://down.51cto.com/data/207112 推荐:你可能需要的在线电子书 ...
- python内置模块(1)
Python的模块在其它语言中通常称为库或类库,也就是lib.它是编程语言的第三级封装,第四级则是包,也就是模块的打包组合,而前两级分别是函数和类.封装的好处,自然不用多言,高内聚,松耦合,减少代码重 ...
- SQL语句技巧之去除重复行
去除表中重复行数据,可能大家立马就想到的是用DISINTCT关键字,但DISINTCT只能是去除表中所有列都相同的行,若碰到需要去除表中多个字段重复的行(即:部份相同,部份不相同),那么该如何做呢?我 ...
- 【推荐】iOS汉字转拼音第三方库
PinYin4Objc是一个在git汉字转拼音的开源库,支持简体和繁体中文.效率POAPinyin等其他库要高,转换库也完整下面简单介绍 实现原理 使用unicode_to_hanyu_pinyin. ...
- thread_Exchanger数据交换
Exchanger 是一个同步辅助类,用于两个并发线程之间在一个同步点进行数据交换. 允许两个线程在某一个点进行数据交换. 可以视作双向的同步队列: 可应用于基因算法.流水线设计等场景 Exchan ...
- ViewData和TempData以及Session的小结
ViewData一般用在从控制器向页面上传递数据. Public ActionResult Show() { ViewData["message"]="你好"; ...
- 泛函编程(24)-泛函数据类型-Monad, monadic programming
在上一节我们介绍了Monad.我们知道Monad是一个高度概括的抽象模型.好像创造Monad的目的是为了抽取各种数据类型的共性组件函数汇集成一套组件库从而避免重复编码.这些能对什么是Monad提供一个 ...
- 利用PBfunc在Powerbuilder中使用https获取微信的AccessToken
在前篇中讲解了使用PBFunc在Powerbuilder自己进行http的GET和POST操作. 本篇简单用代码演示下https的微信AccessToken的获取: n_pbfunc_http lnv ...
- 股票价格涨跌预测—基于KNN分类器
code{white-space: pre;} pre:not([class]) { background-color: white; }if (window.hljs && docu ...
- ahjesus 捕获entity framework生成的sql语句
网上这方面的资料很少,找到一个可以用的 http://code.msdn.microsoft.com/EFProviderWrappers 里面有dll可以下载,有教程,不过是E文的. 在Entity ...