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 

  1. Do not use Thread.stop.

  2. 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的更多相关文章

  1. 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 ...

  2. 《Effective Java》读书笔记 - 10.并发

    Chapter 10 Concurrency Item 66: Synchronize access to shared mutable data synchronized这个关键字不仅保证了同步,还 ...

  3. 【Effective Java】阅读

    Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...

  4. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

  5. Effective Java 67 Avoid excessive synchronization

    Principle To avoid liveness and safety failures, never cede control to the client within a synchroni ...

  6. Effective Java 第三版——8. 避免使用Finalizer和Cleaner机制

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  7. Effective Java 第三版——13. 谨慎地重写 clone 方法

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  8. Effective Java

    Effective Java 创建和销毁对象---考虑用静态工厂方法代替构造器 构造器是创建一个对象实例最基本也最通用的方法,大部分开发者在使用某个class的时候,首先需要考虑的就是如何构造和初始化 ...

  9. Effective Java 15 Minimize mutability

    Use immutable classes as much as possible instead of mutable classes. Advantage Easy to design, impl ...

随机推荐

  1. nodeJS 菜鸟入门

    从一个简单的 HTTP 服务开始旅程-- 创建一个 server.js 文件,写入: //最简单的 http 服务例子 var http = require("http"); ht ...

  2. Android 学习笔记之ContentProvider实现数据共享....

    PS:最近听老师说打算让我参与企业的app制作,让我加快学习的进度...好吧,貌似下周还有考试...貌似实验室这个app也要做...暂时不管了...那就只能加快进度了,感觉略微的有点激动和紧张,总算是 ...

  3. 我的WCF学习与强化系列文章

    1.WCF服务创建与使用(请求应答模式) 2.WCF服务创建与使用(双工模式) 3.WCF序列化 4.WCF实现方法重载 5.WCF会话(Session)与实例(Instance)管理 后面会继续更新 ...

  4. IOS开发UI基础UIView

    主要介绍下UIView得基本概念和一些属性的介绍至于属性的用户后面会由详细的介绍 -.UIView基本概念 1.什么是控件? 屏幕上所有的UI元素都叫做控件 (也有很多书中叫做视图 组件) 比如 按钮 ...

  5. 线段树 + 矩阵 --- ZOJ 3772 Calculate the Function

    Calculate the Function Problem's Link:   http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCod ...

  6. How to remove replication in SyteLine V2

    以前曾经写了一篇<How to remove replication in Syteline>http://www.cnblogs.com/insus/archive/2011/12/20 ...

  7. Linux修改命令提示符(关于环境参量PS1)

    关乎环境参量的四个文件/etc/profile  /etc/bashrc ~/.bashrc  ~/.bash_profile $$$:/etc/profile:此文件为系统的每个用户设置环境信息,当 ...

  8. [moka同学笔记]Yii2.0验证码

    1.Model中Code.php <?php /** * Created by PhpStorm. * User: moka同学 * Date: 2016/07/25 * Time: 10:48 ...

  9. mysql备份方法

    在用PHP或者其他web脚本语言构架的应用系统中,数据库大部分是mysql其中就牵扯到了一个数据库日常备份导出等问题,大概有以下几种情况: 1.如果应用用的是开源的产品,如dz.pw和其他cms等一般 ...

  10. 机器学习实战 - 读书笔记(12) - 使用FP-growth算法来高效发现频繁项集

    前言 最近在看Peter Harrington写的"机器学习实战",这是我的学习心得,这次是第12章 - 使用FP-growth算法来高效发现频繁项集. 基本概念 FP-growt ...