字節跳動一面:i++ 是線程安全的嗎?

點擊上方「 肉眼品世界 」,選擇「 設爲星標

轉自:zemliuhtml

連接:cnblogs.com/zemliu/p/3298685.htmljava

簡介

volatile關鍵字保證了在多線程環境下,被修飾的變量在別修改後會立刻同步到主存,這樣該線程對這個變量的修改就是對全部其餘線程可見的,其餘線程可以立刻讀到這個修改後值.web

Thread的本地內存

  • 每一個Thread都擁有本身的線程存儲空間
  • Thread什麼時候同步本地存儲空間的數據到主存是不肯定的

例子

借用Google JEREMY MANSON 的解釋,上圖表示兩個線程併發執行,並且代碼順序上爲Thread1->Thread2緩存

一、不用 volatile安全

假如ready字段不使用volatile,那麼Thread 1對ready作出的修改對於Thread2來講未必是可見的,是否可見是不肯定的.假如此時thread1 ready泄露了(leak through)了,那麼Thread 2能夠看見ready爲true,可是有可能answer的改變並無泄露,則thread2有可能會輸出 0 (answer=42對thread2並不可見)微信

二、使用 volatile多線程

使用volatile之後,作了以下事情併發

  • 每次修改volatile變量都會同步到主存中
  • 每次讀取volatile變量的值都強制從主存讀取最新的值(強制JVM不可優化volatile變量,如JVM優化後變量讀取會使用cpu緩存而不從主存中讀取)
  • 線程 A 中寫入 volatile 變量以前可見的變量, 在線程 B 中讀取該 volatile 變量之後, 線程 B 對其餘在 A 中的可見變量也可見. 換句話說, 寫 volatile 相似於退出同步塊, 而讀取 volatile 相似於進入同步塊

因此若是使用了volatile,那麼Thread2讀取到的值爲read=>true,answer=>42,固然使用volatile的同時也會增長性能開銷app

注意

volatile並不能保證非源自性操做的多線程安全問題獲得解決,volatile解決的是多線程間共享變量的可見性問題,而例如多線程的i++,++i,依然仍是會存在多線程問題,它是沒法解決了.以下:使用一個線程i++,另外一個i--,最終獲得的結果不爲0編輯器

public class VolatileTest {

    private static volatile int count = 0;
    private static final int times = Integer.MAX_VALUE;

    public static void main(String[] args) {

        long curTime = System.nanoTime();

        Thread decThread = new DecThread();
        decThread.start();

        // 使用run()來運行結果爲0,緣由是單線程執行不會有線程安全問題
        // new DecThread().run();

        System.out.println("Start thread: " + Thread.currentThread() + " i++");

        for (int i = 0; i < times; i++) {
            count++;
        }

        System.out.println("End thread: " + Thread.currentThread() + " i--");

        // 等待decThread結束
        while (decThread.isAlive());

        long duration = System.nanoTime() - curTime;
        System.out.println("Result: " + count);
        System.out.format("Duration: %.2fs\n", duration / 1.0e9);
    }

    private static class DecThread extends Thread {

        @Override
        public void run() {
            System.out.println("Start thread: " + Thread.currentThread() + " i--");
            for (int i = 0; i < times; i++) {
                count--;
            }
            System.out.println("End thread: " + Thread.currentThread() + " i--");
        }
    }
}

最後輸出的結果是

Start thread: Thread[main,5,main] i++Start thread: Thread[Thread-0,5,main] i--End thread: Thread[main,5,main] i--End thread: Thread[Thread-0,5,main] i--Result: -460370604Duration: 67.37s

緣由是i++和++i並不是原子操做,咱們若查看字節碼,會發現

void f1() { i++; }

的字節碼以下

void f1();
Code:
0: aload_0
1: dup
2: getfield #2//Field i:I
5: iconst_1
6: iadd
7: putfield #2//Field i:I
10return

可見i++執行了多部操做, 從變量i中讀取讀取i的值 -> 值+1 -> 將+1後的值寫回i中,這樣在多線程的時候執行狀況就相似以下了

Thread1             Thread2
r1 = i;             r3 = i;
r2 = r1 + 1;        r4 = r3 + 1;
i = r2;             i = r4;

這樣會形成的問題就是 r1, r3讀到的值都是 0, 最後兩個線程都將 1 寫入 i, 最後 i 等於 1, 可是卻進行了兩次自增操做

可知加了volatile和沒加volatile都沒法解決非原子操做的線程同步問題

線程同步問題的解決

Java提供了java.util.concurrent.atomic 包來提供線程安全的基本類型包裝類,例子以下

package com.qunar.atomicinteger;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhenwei.liu created on 2013 13-9-2 下午10:18
 * @version $Id$
 */

public class SafeTest {

    private static AtomicInteger count = new AtomicInteger(0);
    private static final int times = Integer.MAX_VALUE;

    public static void main(String[] args) {

        long curTime = System.nanoTime();

        Thread decThread = new DecThread();
        decThread.start();

        // 使用run()來運行結果爲0,緣由是單線程執行不會有線程安全問題
        // new DecThread().run();

        System.out.println("Start thread: " + Thread.currentThread() + " i++");

        for (int i = 0; i < times; i++) {
            count.incrementAndGet();
        }

        // 等待decThread結束
        while (decThread.isAlive());

        long duration = System.nanoTime() - curTime;
        System.out.println("Result: " + count);
        System.out.format("Duration: %.2f\n", duration / 1.0e9);
    }

    private static class DecThread extends Thread {

        @Override
        public void run() {
            System.out.println("Start thread: " + Thread.currentThread() + " i--");
            for (int i = 0; i < times; i++) {
                count.decrementAndGet();
            }
            System.out.println("End thread: " + Thread.currentThread() + " i--");
        }
    }
}

輸出

Start thread: Thread[main,5,main] i++Start thread: Thread[Thread-0,5,main] i--End thread: Thread[Thread-0,5,main] i--Result: 0Duration: 105.15

結論

  1. volatile解決了線程間共享變量的可見性問題
  2. 使用volatile會增長性能開銷
  3. volatile並不能解決線程同步問題
  4. 解決i++或者++i這樣的線程同步問題須要使用synchronized或者AtomicXX系列的包裝類,同時也會增長性能開銷

本文分享自微信公衆號 - 肉眼品世界(find_world_fine)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索