zoukankan      html  css  js  c++  java
  • 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 

    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.

  • 相关阅读:
    Android开发之 Android 的基本组件的概述
    Android开发之 Android应用程序详细解析
    Android开发之 Android应用程序目录结构解析
    第七篇 :微信公众平台开发实战Java版之如何获取微信用户基本信息
    Android 开发之Windows环境下Android Studio安装和使用教程(图文详细步骤)
    Android开发之 Windows环境下通过Eclipse创建的第一个安卓应用程序(图文详细步骤)
    Android 开发之 Android 开发的起步
    Github学习进阶-初露锋芒,通过命令行将本地git仓库推送到Github上面的仓库
    Windows环境下maven 安装与环境变量配置
    Github学习之路-小试牛刀,练习Git 的基本操作
  • 原文地址:https://www.cnblogs.com/haokaibo/p/synchronize-access-to-shared-mutable-data.html
Copyright © 2011-2022 走看看