Core Java 并发:理解并发概念

个人博客请访问 http://www.x0100.top 

1. 简介

从诞生开始,Java 就支持线程、锁等关键的并发概念。这篇文章旨在为使用了多线程的 Java 开发者理解 Core Java 中的并发概念以及使用方法。

2. 概念

2.1 竞争条件

多个线程对共享资源执行一系列操作,根据每个线程的操作顺序可能存在几种结果,这时出现竞争条件。下面的代码不是线程安全的,而且可以不止一次地初始化 value,因为 check-then-act(检查 null,然后初始化),所以延迟初始化的字段不具备原子性:

class Lazy <T> {

    private volatile T value;

    T get() {

      if (value == null)

        value = initialize();

      return value;

    }

 }

2.2 数据竞争

两个或多个线程试图访问同一个非 final 变量并且不加上同步机制,这时会发生数据竞争。没有同步机制可能导致这样的情况,线程执行过程中做出其他线程无法看到的更改,因而导致读到修改前的数据。这样反过来可能又会导致无限循环、破坏数据结构或得到错误的计算结果。下面这段代码可能会无限循环,因为读线程可能永远不知道写线程所做的更改:

  1. class Waiter implements Runnable {

  2.  private boolean shouldFinish;

  3.  void finish() { shouldFinish = true; }

  4.  public void run() {

  5.    long iteration = 0;

  6.    while (!shouldFinish) {

  7.      iteration++;

  8.    }

  9.    System.out.println("Finished after: " + iteration);

  10.  }

  11. }

  12.  

  13. class DataRace {

  14.  public static void main(String[] args) throws InterruptedException {

  15.    Waiter waiter = new Waiter();

  16.    Thread waiterThread = new Thread(waiter);

  17.    waiterThread.start();

  18.    waiter.finish();

  19.    waiterThread.join();

  20.  }

  21. }

3. Java 内存模型:happens-before 关系

Java 内存模型定义基于一些操作,比如读写字段、 Monitor 同步等。这些操作可以按照 happens-before 关系进行排序。这种关系可用来推断一个线程何时看到另一个线程的操作结果,以及构成一个程序同步后的所有信息。

happens-before 关系具备以下特性:

  • 在线程开始所有操作前调用 Thread#start

  • 在获取 Monitor 前,释放该 Monitor

  • 在读取 volatile 变量前,对该变量执行一次写操作

  • 在写入 final 变量前,确保在对象引用已存在

  • 线程中的所有操作应在 Thread#join 返回之前完成

4. 标准同步特性

4.1 synchronized 关键字

使用 synchronized 关键字可以防止不同线程同时执行相同代码块。由于进入同步执行的代码块之前加锁,受该锁保护的数据可以在排他模式下操作,从而让操作具备原子性。此外,其他线程在获得相同的锁后也能看到操作结果。

  1. class AtomicOperation {

  2.  private int counter0;

  3.  private int counter1;

  4.  void increment() {

  5.    synchronized (this) {

  6.      counter0++;

  7.      counter1++;

  8.    }

  9.  }

  10. }

也可以在方法上加 synchronized 关键字。

表2 当整个方法都标记 synchronized 时使用的 Monitor

锁是可重入的。如果线程已经持有锁,它可以再次成功地获得该锁。

  1. class Reentrantcy {

  2.  synchronized void doAll() {

  3.    doFirst();

  4.    doSecond();

  5.  }

  6.  synchronized void doFirst() {

  7.    System.out.println("First operation is successful.");

  8.  }

  9.  synchronized void doSecond() {

  10.    System.out.println("Second operation is successful.");

  11.  }

  12. }

竞争的程度对获取 Monitor 的方式有影响:

表3: Monitor 状态

4.2 wait/notify

wait/notify/notifyAll 方法在 Object 类中声明。如果之前设置了超时,线程进入 WAITING 或 TIMED_WAITING 状态前保持 wait状态。要唤醒一个线程,可以执行下列任何操作:

  • 另一个线程调用 notify 将唤醒任意一个在 Monitor 上等待的线程。

  • 另一个线程调用 notifyAll 将唤醒所有在等待 Monitor 上等待的线程。

  • 调用 Thread#interrupt 后会抛出 InterruptedException 异常。

最常见的模式是条件循环:

  1. class ConditionLoop {

  2.  private boolean condition;

  3.  synchronized void waitForCondition() throws InterruptedException {

  4.    while (!condition) {

  5.      wait();

  6.    }

  7.  }

  8.  synchronized void satisfyCondition() {

  9.    condition = true;

  10.    notifyAll();

  11.  }

  12. }

  • 请记住,在对象上调用 wait/notify/notifyAll,需要首先获得该对象的锁

  • 在检查等待条件的循环中保持等待:这解决了另一个线程在等待开始之前即满足条件时的计时问题。 此外,这样做还可以让你的代码免受可能(也的确会)发生的虚假唤醒

  • 在调用 notify/notifyAll 前,要确保满足等待条件。如果不这样做会引发通知,然而没有线程能够避免等待循环

4.3 volatile 关键字

volatile 解决了可见性问题,让修改成为原子操作。由于存在 happens-before 关系,在接下来读取 volatile 变量前,先对 volatile 变量进行写操作。 从而保证了对该字段的任何读操作都能督读到最近一次修改后的值。

  1. class VolatileFlag implements Runnable {

  2.  private volatile boolean shouldStop;

  3.  public void run() {

  4.    while (!shouldStop) {

  5.      // 执行操作

  6.    }

  7.    System.out.println("Stopped.");

  8.  }

  9.  void stop() {

  10.    shouldStop = true;

  11.  }

  12.  public static void main(String[] args) throws InterruptedException {

  13.    VolatileFlag flag = new VolatileFlag();

  14.    Thread thread = new Thread(flag);

  15.    thread.start();

  16.    flag.stop();

  17.    thread.join();

  18.  }

  19. }

4.4 Atomic

java.util.concurrent.atomic package 包含了一组类,它们用类似 volatile 的无锁方式支持单个值的原子复合操作。

使用 AtomicXXX 类,可以实现 check-then-act 原子操作:

  1. class CheckThenAct {

  2.  private final AtomicReference<String> value = new AtomicReference<>();

  3.  void initialize() {

  4.    if (value.compareAndSet(null, "Initialized value")) {

  5.      System.out.println("Initialized only once.");

  6.    }

  7.  }

  8. }

AtomicInteger 和 AtomicLong 都提供原子 increment/decrement 操作:

  1. class Increment {

  2.  private final AtomicInteger state = new AtomicInteger();

  3.  void advance() {

  4.    int oldState = state.getAndIncrement();

  5.    System.out.println("Advanced: '" + oldState + "' -> '" + (oldState + 1) + "'.");

  6.  }

  7. }

如果你希望有这样一个计数器,不需要在获取计数的时候具备原子性,可以考虑用 LongAdder 取代 AtomicLong/AtomicInteger。 LongAdder 能在多个单元中存值并在需要时增加计数,因此在竞争激烈的情况下表现更好。

4.5 ThreadLocal

一种在线程中包含数据但不用锁的方法是使用 ThreadLocal 存储。从概念上讲,ThreadLocal 可以看做每个 Thread 存有一份自己的变量。Threadlocal 通常用于保存每个线程的值,比如“当前事务”或其他资源。 此外,还可以用于维护每个线程的计数器、统计信息或 ID 生成器。

  1. class TransactionManager {

  2.  private final ThreadLocal<Transaction> currentTransaction

  3.      = ThreadLocal.withInitial(NullTransaction::new);

  4.  Transaction currentTransaction() {

  5.    Transaction current = currentTransaction.get();

  6.    if (current.isNull()) {

  7.      current = new TransactionImpl();

  8.      currentTransaction.set(current);

  9.    }

  10.    return current;

  11.  }

  12. }

5. 安全地发布对象

想让一个对象在当前作用域外使用可以发布对象,例如从 getter 返回该对象的引用。 要确保安全地发布对象,仅在对象完全构造好后发布,可能需要同步。 可以通过以下方式安全地发布:

  • 静态初始化器。只有一个线程可以初始化静态变量,因为类的初始化在获取排他锁条件下完成。

  1. class StaticInitializer {

  2.  // 无需额外初始化条件,发布一个不可变对象

  3.  public static final Year year = Year.of(2017);

  4.  public static final Set<String> keywords;

  5.  // 使用静态初始化器构造复杂对象

  6.  static {

  7.    // 创建可变集合

  8.    Set<String> keywordsSet = new HashSet<>();

  9.    // 初始化状态

  10.    keywordsSet.add("java");

  11.    keywordsSet.add("concurrency");

  12.    // 设置 set 不可修改

  13.    keywords = Collections.unmodifiableSet(keywordsSet);

  14.  }

  15. }

  • volatile 字段。由于写入 volatile 变量发生在读操作之前,因此读线程总能读到最新的值。

  1. class Volatile {

  2.  private volatile String state;

  3.  void setState(String state) {

  4.    this.state = state;

  5.  }

  6.  String getState() {

  7.    return state;

  8.  }

  9. }

  • Atomic。例如 AtomicInteger 将值存储在 volatile 字段中,所以 volatile 变量的规则在这里也适用。

  1. class Atomics {

  2.  private final AtomicInteger state = new AtomicInteger();

  3.  void initializeState(int state) {

  4.    this.state.compareAndSet(0, state);

  5.  }

  6.  int getState() {

  7.    return state.get();

  8.  }

  9. }

  • final 字段

  1. class Final {

  2.  private final String state;

  3.  Final(String state) {

  4.    this.state = state;

  5.  }

  6.  String getState() {

  7.    return state;

  8.  }

  9. }

确保在对象构造期间不会修改此引用。

  1. class ThisEscapes {

  2. private final String name;

  3. ThisEscapes(String name) {

  4.   Cache.putIntoCache(this);

  5.   this.name = name;

  6. }

  7. String getName() { return name; }

  8. }

  9. class Cache {

  10. private static final Map<String, ThisEscapes> CACHE = new ConcurrentHashMap<>();

  11. static void putIntoCache(ThisEscapes thisEscapes) {

  12.   // 'this' 引用在对象完全构造之前发生了改变

  13.   CACHE.putIfAbsent(thisEscapes.getName(), thisEscapes);

  14. }

  15. }

  • 正确同步字段

  1. class Synchronization {

  2.  private String state;

  3.  synchronized String getState() {

  4.    if (state == null)

  5.      state = "Initial";

  6.    return state;

  7.  }

  8. }

6. 不可变对象

不可变对象的一个重要特征是线程安全,因此不需要同步。要成为不可变对象:

  • 所有字段都标记 final

  • 所有字段必须是可变或不可变的对象,注意不要改变对象作用域,否则构造后不能改变对象状态

  • this 引用在构造对象时不要泄露

  • 类标记 final,子类无法重载改变类的行为

  • 不可变对象示例:

  1. // 标记为 final,禁止继承

  2. public final class Artist {

  3.  // 不可变变量,字段标记 final

  4.  private final String name;

  5.  // 不可变变量集合, 字段标记 final

  6.  private final List<Track> tracks;

  7.  public Artist(String name, List<Track> tracks) {

  8.    this.name = name;

  9.    // 防御性拷贝

  10.    List<Track> copy = new ArrayList<>(tracks);

  11.    // 使可变集合不可修改

  12.    this.tracks = Collections.unmodifiableList(copy);

  13.    // 构造对象期间,'this' 不传递到任何其他地方

  14.  }

  15.  // getter、equals、hashCode、toString 方法

  16. }

  17. // 标记为 final,禁止继承

  18. public final class Track {

  19.  // 不可变变量,字段标记 final

  20.  private final String title;

  21.  public Track(String title) {

  22.    this.title = title;

  23.  }

  24.  // getter、equals、hashCode、toString 方法

  25. }

7. 线程

java.lang.Thread 类用于表示应用程序线程或 JVM 线程。 代码始终在某个 Thread 类的上下文中执行,使用 Thread#currentThread() 可返回自己的当前线程。

表4 线程状态

表5 线程协调方法

7.1 如何处理 InterruptedException?

  • 清理所有资源,并在当前运行级别尽可能能完成线程执行

  • 当前方法声明抛出 InterruptedException。

  • 如果方法没有声明抛出 InterruptedException,那么应该通过调用 Thread.currentThread().interrupt() 将中断标志恢复为 true。 并且在这个级别上抛出更合适的异常。为了能在更高调用级别上处理中断,把中断标志设置为 true 非常重要

7.2 处理意料之外的异常

线程可以指定一个 UncaughtExceptionHandler 接收由于发生未捕获异常导致线程突然终止的通知。

  1. Thread thread = new Thread(runnable);

  2. thread.setUncaughtExceptionHandler((failedThread, exception) -> {

  3.  logger.error("Caught unexpected exception in thread '{}'.",

  4.      failedThread.getName(), exception);

  5. });

  6. thread.start();

8. 活跃度

8.1 死锁

有多个线程,每个线程都在等待另一个线程持有的资源,形成一个获取资源的线程循环,这时会发生死锁。最典型的资源是对象 Monitor ,但也可能是任何可能导致阻塞的资源,例如 wait/notify。

下面的代码可能产生死锁:

  1. class Account {

  2.  private long amount;

  3.  void plus(long amount) { this.amount += amount; }

  4.  void minus(long amount) {

  5.    if (this.amount < amount)

  6.      throw new IllegalArgumentException();

  7.    else

  8.      this.amount -= amount;

  9.  }

  10.  static void transferWithDeadlock(long amount, Account first, Account second){

  11.    synchronized (first) {

  12.      synchronized (second) {

  13.        first.minus(amount);

  14.        second.plus(amount);

  15.      }

  16.    }

  17.  }

  18. }

如果同时出现以下情况,就会发生死锁:

  • 一个线程正试图从第一个帐户切换到第二个帐户,并已获得了第一个帐户的锁

  • 另一个线程正试图从第二个帐户切换到第一个帐户,并已获得第二个帐户的锁

避免死锁的方法:

  • 按顺序加锁:总是以相同的顺序获取锁

  1. class Account {

  2.  private long id;

  3.  private long amount;

  4.  // 此处略去了一些方法

  5.  static void transferWithLockOrdering(long amount, Account first, Account second){

  6.    boolean lockOnFirstAccountFirst = first.id < second.id;

  7.    Account firstLock = lockOnFirstAccountFirst  ? first  : second;

  8.    Account secondLock = lockOnFirstAccountFirst ? second : first;

  9.    synchronized (firstLock) {

  10.      synchronized (secondLock) {

  11.        first.minus(amount);

  12.        second.plus(amount);

  13.      }

  14.    }

  15.  }

  16. }

  • 锁定超时:获取锁时不要无限期阻塞,而是释放所有锁并重试

  1. class Account {

  2.  private long amount;

  3.  // 此处略去了一些方法

  4.  static void transferWithTimeout(

  5.      long amount, Account first, Account second, int retries, long timeoutMillis

  6.  ) throws InterruptedException {

  7.    for (int attempt = 0; attempt < retries; attempt++) {

  8.      if (first.lock.tryLock(timeoutMillis, TimeUnit.MILLISECONDS))

  9.      {

  10.        try {

  11.          if (second.lock.tryLock(timeoutMillis, TimeUnit.MILLISECONDS))

  12.          {

  13.            try {

  14.              first.minus(amount);

  15.              second.plus(amount);

  16.            }

  17.            finally {

  18.              second.lock.unlock();

  19.            }

  20.          }

  21.        }

  22.        finally {

  23.          first.lock.unlock();

  24.        }

  25.      }

  26.    }

  27.  }

  28. }

Jvm 能够检测 Monitor 死锁,并以线程转储的形式打印死锁信息。

8.2 活锁与线程饥饿

当线程将所有时间用于协商资源访问或者检测避免死锁,以至于没有线程能够访问资源时,会造成活锁(Livelock)。 线程饥饿发生在线程长时间持锁,导致一些线程无法继续执行被“饿死”。

9. java.util.concurrent

9.1 线程池

线程池的核心接口是 ExecutorService。 java.util.concurrent 还提供了一个静态工厂类 Executors,其中包含了新建线程池的工厂方法,新建的线程池参数采用最常见的配置。

表6 静态工厂方法

译注:在并行计算中,work-stealing 是一种针对多线程计算机程序的调度策略。 它解决了在具有固定数量处理器或内核的静态多线程计算机上执行动态多线程计算的问题,这种计算可以“产生”新的执行线程。 在执行时间、内存使用和处理器间通信方面都能够高效地完成任务。

在调整线程池的大小时,通常需要根据运行应用程序的计算机中的逻辑核心数量来确定线程池的大小。 在 Java 中,可以通过调用 Runtime.getRuntime().availableProcessors() 读取。

表7 线程池实现

可通过 ExecutorService#submit、ExecutorService#invokeAll 或 ExecutorService#invokeAny 提交任务,可根据不同任务进行多次重载。

表8 任务的功能接口

9.2 Future

Future 是对异步计算的一种抽象,代表计算结果。计算结果可能是某个计算值或异常。ExecutorService 的大多数方法都使用 Future 作为返回类型。使用 Future 时,可通过提供的接口检查当前状态,或者一直阻塞直到结果计算完成。

  1. ExecutorService executorService = Executors.newSingleThreadExecutor();

  2. Future<String> future = executorService.submit(() -> "result");

  3. try {

  4.  String result = future.get(1L, TimeUnit.SECONDS);

  5.  System.out.println("Result is '" + result + "'.");

  6. }

  7. catch (InterruptedException e) {

  8.  Thread.currentThread().interrupt();

  9.  throw new RuntimeException(e);

  10. }

  11. catch (ExecutionException e) {

  12.  throw new RuntimeException(e.getCause());

  13. }

  14. catch (TimeoutException e) {

  15.  throw new RuntimeException(e);

  16. }

  17. assert future.isDone();

9.3 锁

9.3.1 Lock

java.util.concurrent.locks package 提供了标准 Lock 接口。ReentrantLock 在实现 synchronized 关键字功能的同时还包含了其他功能,例如获取锁的状态信息、非阻塞 tryLock() 和可中断锁定。直接使用 ReentrantLock 示例如下:

  1. class Counter {

  2.  private final Lock lock = new ReentrantLock();

  3.  private int value;

  4.  int increment() {

  5.    lock.lock();

  6.    try {

  7.      return ++value;

  8.    } finally {

  9.      lock.unlock();

  10.    }

  11.  }

  12. }

9.3.2 ReadWriteLock

java.util.concurrent.locks package 还包含 ReadWriteLock 接口(以及 Reentrantreadelock 实现)。该接口定义了一对锁进行读写操作,通常支持多个并发读取,但只允许一个写入。

  1. class Statistic {

  2.  private final ReadWriteLock lock = new ReentrantReadWriteLock();

  3.  private int value;

  4.  void increment() {

  5.    lock.writeLock().lock();

  6.    try {

  7.      value++;

  8.    } finally {

  9.      lock.writeLock().unlock();

  10.    }

  11.  }

  12.  int current() {

  13.    lock.readLock().lock();

  14.    try {

  15.      return value;

  16.    } finally {

  17.      lock.readLock().unlock();

  18.    }

  19.  }

  20. }

9.3.3 CountDownLatch

CountDownLatch 用一个计数器初始化。线程可以调用 await() 等待计数归零。其他线程(或同一线程)可能会调用 countDown() 来减小计数。一旦计数归零即不可重用。CountDownLatch 用于发生某些操作时触发一组未知的线程。

9.3.4 CompletableFuture

CompletableFuture 是对异步计算的一种抽象。 与普通 Future 不同,CompletableFuture 仅支持阻塞方式获得结果。当结果产生或发生异常时,执行由已注册的回调函数创建的任务管道。无论是创建过程中(通过 CompletableFuture#supplyAsync/runAsync),还是在加入回调过程中( *async 系列方法),如果没有指定标准的全局 ForkJoinPool#commonPool 都可以设置执行计算的执行器。

考虑 CompletableFuture 已执行完毕,那么通过非 async 方法注册的回调将在调用者的线程中执行。

如果程序中有几个 future,可以使用 CompletableFuture#allOf 获得一个 future,这个 future 在所有 future 完成时结束。也可以调用 CompletableFuture#anyOf 获得一个 future,这个 future 在其中任何一个 future 完成时结束。

  1. ExecutorService executor0 = Executors.newWorkStealingPool();

  2. ExecutorService executor1 = Executors.newWorkStealingPool();

  3. // 当这两个 future 完成时结束

  4. CompletableFuture<String> waitingForAll = CompletableFuture

  5.    .allOf(

  6.        CompletableFuture.supplyAsync(() -> "first"),

  7.        CompletableFuture.supplyAsync(() -> "second", executor1)

  8.    )

  9.    .thenApply(ignored -> " is completed.");

  10. CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> "Concurrency Refcard", executor0)

  11.    // 使用同一个 executor

  12.    .thenApply(result -> "Java " + result)

  13.    // 使用不同的 executor

  14.    .thenApplyAsync(result -> "Dzone " + result, executor1)

  15.    // 当前与其他 future 完成后结束

  16.    .thenCombine(waitingForAll, (first, second) -> first + second)

  17.    // 默认使用 ForkJoinPool#commonPool 作为 executor

  18.    .thenAcceptAsync(result -> {

  19.      System.out.println("Result is '" + result + "'.");

  20.    })

  21.    // 通用处理

  22.    .whenComplete((ignored, exception) -> {

  23.      if (exception != null)

  24.        exception.printStackTrace();

  25.    });

  26. // 第一个阻塞调用:在 future 完成前保持阻塞

  27. future.join();

  28. future

  29.    // 在当前线程(main)中执行

  30.    .thenRun(() -> System.out.println("Current thread is '" + Thread.currentThread().getName() + "'."))

  31.    // 默认使用 ForkJoinPool#commonPool 作为 executor

  32.    .thenRunAsync(() -> System.out.println("Current thread is '" + Thread.currentThread().getName() + "'."))

9.4 并发集合

使集合线程安全最简单方法是使用 Collections#synchronized* 系列方法。 由于这种解决方案在竞争激烈的情况下性能很差,所以 java.util.concurrent 提供了多种针对并发优化的数据结构。

9.4.1 List

表9:java.util.concurrent 中的 Lists

译注:copy-on-write(写入时复制)是一种计算机程序设计领域的优化策略。其核心思想是,如果有多个调用者同时请求相同资源(如内存或磁盘上的数据存储),他们会共同获取相同的指针指向相同的资源,直到某个调用者试图修改资源的内容时,系统才会真正复制一份专用副本给该调用者,而其他调用者所见到的最初的资源仍然保持不变。这个过程对其他的调用者透明。这种做法的主要优点是如果调用者没有修改该资源,就不会新建副本,因此多个调用者只是读取操作可以共享同一份资源。

9.4.2 Map

表10 java.util.concurrent 中的 Map

9.4.3 Set

表11 java.util.concurrent 中的 Set

封装 concurrent map 进而创建 concurrent set 的另一种方法:

  1. Set<T> concurrentSet = Collections.newSetFromMap(new ConcurrentHashMap<T, Boolean>());

9.4.4 Queue

队列就像是“生产者”和“消费者”之间的管道。按照“先进先出(FIFO)”顺序,将对象从管道的一端加入,从管道的另一端取出。BlockingQueue 接口继承了 Queue接口,并且增加了(生产者添加对象时)队列满或(消费者读取或移除对象时)队列空的处理。 在这些情况下,BlockingQueue 提供的方法可以一直保持或在一段时间内保持阻塞状态,直到等待的条件由另一个线程的操作改变。

表12 java.util.concurrent 中的 Queue

更多精彩内容扫描下方二维码进入网站。。。。。

关注微信公众号。。。。。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值