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 ...
随机推荐
- Javascript刷新页面的八种方法
/** * Javascript刷新页面的八种方法 * 说明一下,jQuery没有发现刷新页面的方法. */ 1 history.go(0) 2 location.reload() 3 locatio ...
- MEF(Managed Extensibility Framework )的入门介绍
1.什么是MEF MEF是一个来自于微软协作构建扩展应用的新框架,它的目的是在运行中的应用中添加插件.MEF继承于.NET 4.0 Framework平台,存在于各种应用平台的系统程序集中 2.程序集 ...
- 组合数学 - 母函数的运用 --- hdu 1709 :The Balance
The Balance Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total ...
- MVC bundle(包扎)CSS或是JS文件
以前写asp.net网页时,会在<head>节点中引用很多样式文件或是javascript文件,如下图左大括号的引用语句. 现在在MVC应用程序中,可以使用使用Bundle来捆一起, 在S ...
- Python基础:序列
一.概述 序列类型(Sequence Types)类似于C中的数组,它是包含一组成员的连续列表,这些成员紧邻排列,并且可以通过序号(下标偏移量)访问其中的一个或多个成员.序列类型的示意图如下所示: P ...
- Winfrom中ListBox绑定List数据源更新问题
Winfrom中ListBox绑定List数据源更新问题 摘自:http://xiaocai.info/2010/09/winform-listbox-datasource-update/ Winfr ...
- csharp: Export or Import excel using NPOI
excel 2003: using System; using System.Collections.Generic; using System.ComponentModel; using Syste ...
- lavarel框架中如何使用ajax提交表单
开门见山,因为laravel以post形式提交数据时候需要加{{csrf_field()}}防止跨站攻击,所以当你用ajax提交表单时候自然也要加 在网上看了很多的解决方式,我是用下面这种方法解决的: ...
- 【转】RBAC权限管理
RBAC(Role-Based Access Control,基于角色的访问控制),就是用户通过角色与权限进行关联.简单地说,一个用户拥有若干角色,每一个角色拥有若干权限.这样,就构造成“用户-角色- ...
- HDU 1069---背包---Monkey and Banana
HDU 1069 Description A group of researchers are designing an experiment to test the IQ of a monkey. ...