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. [mysql]MySQL忘记密码

    1.修改MySQL的登录设置: vi /etc/my.cnf 在[mysqld]的段中加上一句:skip-grant-tables 保存并且退出vi. 2.重新启动mysqld # /etc/init ...

  2. Laravel 5 事件的使用

    事件类通常被保存在 app/Events 目录下,而它们的处理程序则被保存在 app/Handlers/Events 目录下. 事件的创建 下面我们用artisan来创建一个事件,比如叫CqhTest ...

  3. ASP.NET MVC 使用 IOC框架 AutoFac 自动释放数据库资源

    每次使用using或者dispose来释放资源会比较麻烦,作为一个会偷懒的程序员来说当然不能接受了. 一.引用 autofac.dll和autofac.integration.mvc.dll 二.打开 ...

  4. SQL Server技术问题之游标优缺点

    分类: MS SQL SERVER 支持三种类型的游标:Transact_SQL 游标,API 服务器游标和客户游标. (1) Transact_SQL 游标 Transact_SQL 游标是由DEC ...

  5. 【转】Python中的GIL、多进程和多线程

    转自:http://lesliezhu.github.io/public/2015-04-20-python-multi-process-thread.html 目录 1. GIL(Global In ...

  6. CSS布局 -- 左右定宽,中间自适应

    左右定宽,中间自适应 有几种方法可以实现 改变窗口大小看看? 方案一: 左右设置绝对定位,定宽,中间设置margin-left  margin-right 查看 demo <!DOCTYPE h ...

  7. 重构第31天 使用多态替代条件语句( Replace conditional with Polymorphism)

    理解:本文中的”使用多态代替条件判断”是指如果你需要检查对象的类型或者根据类型执行一些操作时,一种很好的办法就是将算法封装到类中,并利用多态性进行抽象调用. 详解:本文展示了面向对象编程的基础之一“多 ...

  8. visual studio 局域网远程调试web项目

    1.进入项目根目录,找到.vs/config/applicationhost.config文件(可能是隐藏的) 2.搜索sites节点,找到当前项目,并添加一个binding配置节,将ip地址设置为本 ...

  9. Winform开发框架之简易工作流设计

    一讲到工作流,很多人第一反应就是这个东西很深奥,有时候又觉得离我们较为遥远,确实完善的工作流设计很多方面,而正是由于需要兼顾很多方面,一般通用的工作流都难做到尽善尽美.微软也提供了几个版本的WF框架支 ...

  10. (三)XmlHelper

    [转]http://blog.csdn.net/u011866450/article/details/50373222 using System.Xml; using System.Data; nam ...