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. SQL Server里的INTERSECT ALL

    在上一篇文章里,我讨论了INTERSECT设置操作的基础,它和INNER JOIN的区别,还有为什么需要好的索引设计支持.今天我想谈下SQL Server里并未实现的INTERSECT ALL操作. ...

  2. fpmmm(mpm)监控mysql模块安装

    zabbix mpm监控mysql是一个蛮不错的监控模块,不过最近官网已经不叫mpm了,而是叫fpmmm,理由为: fpmmm is the successor of mpm. mpm was ren ...

  3. R语言简单聚类分析

    #以R基础包自带的鸢尾花(Iris)数据进行聚类分析iris data <- iris[,:] #系统聚类法(层次聚类法) distance <- dist(data) #计算距离 iri ...

  4. jQuery的事件one

    如果你只想你设计的对象只能让用户执行一次的话,可以使用jQuery的事件one()来实现. 演示一个,创建视图, 看看效果:

  5. 新学C#线程使用总结

    这两天在项目上需要使用多线程技术,研究了半天,碰到了一些问题,现在简要总结下. 线程的使用其实很简单,和JAVA里面差不多,但是还是有很多特别的地方,在C#中的线程,如果要对非线程创建的控件进行操作的 ...

  6. Python基础:元类

    一.概述 二.经典阐述 三.核心总结 1.类的创建过程 2.元类的使用惯例 四.简单案例 1.默认行为 2.使用元类 五.实践为王 一.概述 Python虽然是多范式的编程语言,但它的数据模型却是 纯 ...

  7. sphinx配置文件sphinx.conf参数详细说明

    sphinx配置文件sphinx.conf参数详细说明 sphinx.conf各个参数详细说明 # # Sphinx configuration file sample # # WARNING! Wh ...

  8. 回文串---Hotaru's problem

    HDU   5371 Description Hotaru Ichijou recently is addicated to math problems. Now she is playing wit ...

  9. 泛函编程(6)-数据结构-List基础

    List是一种最普通的泛函数据结构,比较直观,有良好的示范基础.List就像一个管子,里面可以装载一长条任何类型的东西.如需要对管子里的东西进行处理,则必须在管子内按直线顺序一个一个的来,这符合泛函编 ...

  10. No.003:Longest Substring Without Repeating Characters

    问题: Given a string, find the length of the longest substring without repeating characters.Example:Gi ...