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. 用emacs的org2blog组件写cnblogs博客 -- 环境配置及使用

    Table of Contents 配置 使用 创建一篇博文并发布 更新一篇博文 删除一篇博文 待办 本文给出了一个安装.配置org2blog的方法,实现在emacs中书写blog文章.并发布到cnb ...

  2. 第十二篇 SQL Server代理多服务器管理

    本篇文章是SQL Server代理系列的第十二篇,详细内容请参考原文 在这一系列的上一篇,我们查看了维护计划,一个维护计划可能会创建多个作业,多个计划.你还简单地看了SSIS子系统,并查看了维护计划作 ...

  3. 开源一个基于天天团购的团购app

    可能大家都知道天天团购开源系统,一个做团购的开源项目很赞,前些日子做了基于天天团购系统做的团购客户端和移动端服务器!源代码放出,有了解的可以看看,希望收益! 先说服务器:app的服务器,基于天天团购的 ...

  4. 一起Polyfill系列:Function.prototype.bind的四个阶段

    昨天边参考es5-shim边自己实现Function.prototype.bind,发现有不少以前忽视了的地方,这里就作为一个小总结吧. 一.Function.prototype.bind的作用 其实 ...

  5. 什么是https?

    很久之前注意到了https这个新出来的协议,当时感觉到只是一个加密的协议,然后没有什么关注,只知道他和http的区别就在于加密,最近突然很多人问起了这个https到底是什么?于是上网查了查资料,总结之 ...

  6. 44个 Javascript 变态题解析 (上\下)

    第1题 ["1", "2", "3"].map(parseInt) 知识点: Array/map Number/parseInt JavaS ...

  7. sprint3(第四天)

    今天继续完成前台和后台的整合 燃尽图:

  8. HTTP请求响应报文&&相关状态码&&GET_POST请求方法 总结

    HTTP请求报文: 一个HTTP请求报文由四个部分组成:请求行.请求头部.空行.请求数据 1.请求行   请求行由请求方法字段.URL字段和HTTP协议版本字段3个字段组成,它们用空格分隔.比如 GE ...

  9. Jquery Validation 多按钮,多表单,分组验证

    真正做到了 多按钮的验证. 在用户输入的时候就可以验证,而网上大部分多按钮验证都是必须要用户点击按钮后才可以验证. 研究了两天终于弄出来了,不知道两天是过长还是过段,现在分享给小伙伴们. 小伙伴们支持 ...

  10. PHP实现文字水印图片

    php实现简单的文字水印图片,使用前需要开启php配置中的gd2功能 <?php/*打开图片*/ //1.配置图片路径 $src="image/55.jpg";//这个路径改 ...