Java 线程(4)- 线程同步工具

Minorca, Spain by @jeztimms

发布共享变量

延迟加载(Lazy Initialization)

public class SafeLazyInitialization {
     private static Resource resource;
     public synchronized static Resource getInstance() {
         if (resource == null)
            resource = new Resource();
         return resource;
    }
}

//Lazy Initialization with Holder Class Idiom
public class ResourceFactory {
     private static class ResourceHolder {
        public static Resource resource = new Resource();
     }
     public static Resource getResource() {
        return ResourceHolder.resource ;
     }
}

立即加载(Eager Initialization)

public class EagerInitialization {
    private static Resource resource = new Resource();
    public static Resource getResource() { return resource; }
}

Double-Checked-Locking (Anti-pattern, Don't Do this)

public class DoubleCheckedLocking {
     private static Resource resource; //using volatile can fix this problem 
     
     public static Resource getInstance() {
         if (resource == null) {
            synchronized (DoubleCheckedLocking.class) {
                if (resource == null)
                    resource = new Resource();
            }
         }
         return resource;
     }
}

Synchronizers

Java 内置的 Synchronizers 包括

Latches

A latch is a synchronizer that can delay the progress of threads until it reaches its terminal state [CPJ 3.4.2].

  • java.util.concurrent.CountDownLatch,确保一个计算直到某些资源或服务就绪后才开始
  • java.util.concurrent.FutureTask (Promise)

Semaphore (控制集合边界)

Counting semaphores are used to control the number of activities that can access a certain resource or perform a given action at the same time [CPJ 3.4.1]

  • java.util.concurrent.Semaphore

Barriers (线程之间的互相等待)

Barriers are similar to latches in that they block a group of threads until some event has occurred [CPJ 4.4.3]. The key difference is that with a barrier, all the threads must come together at a barrier point at the same time in order to proceed. Latches are for waiting for events; barriers are for waiting for other threads.

  • java.util.concurrent.CyclicBarrier
  • java.util.concurrent.Phaser

自定义同步工具

注意:只用 Java 内置的并发工具无法满足要求时才应该考虑

进入和退出协议(Entry and Exit Protocols)

The entry protocol is the operation's condition predicate; the exit protocol involves examining any state variables that have been changed by the operation to see if they might have caused some other condition predicate to become true, and if so, notifying on the associated condition queue.

原始实现:

void blockingAction() throws InterruptedException { 
    // acquire lock on object state 
    while (precondition does not hold) { 
        // release lock 
        // wait until precondition might hold, then reacquire lock and break
        // (optionally fail if interrupted or timeout expires)
    } 
    // perform action
    // release lock
}

使用 wait-notify/notifyAll 实现:

public class BoundedBuffer<V> extends BaseBoundedBuffer<V> { 
    // CONDITION PREDICATE: not-full (!isFull()) 
    // CONDITION PREDICATE: not-empty (!isEmpty()) 
    public BoundedBuffer(int size) { super(size); } 
    // BLOCKS-UNTIL: not-full 
    public synchronized void put(V v) throws InterruptedException { 
        while (isFull()) 
            wait(); 
        doPut(v); 
        notifyAll(); 
    } 
    // BLOCKS-UNTIL: not-empty 
    public synchronized V take() throws InterruptedException { 
        while (isEmpty()) 
            wait(); 
        V v = doTake(); 
        notifyAll(); 
        return v; 
    } 
}

实现时的注意:

  • 推荐使用 notifyAll() 而不是 notify(),因为单个通知容易出现类似于丢失信号的问题并且多个线程可能在相同条件队列上等待不同的先前条件(condition predicates),notifyAll() 可能造成只有 n 个线程,却通知 O(n^2) 次
  • wait 方法应该在循环中调用以避免过早唤醒或错过信号
    void stateDependentMethod() throws InterruptedException { 
        // condition predicate must be guarded by lock
        synchronized(lock) {
            while (!conditionPredicate())
                lock.wait();
            // object is now in desired state
        }
    }
    
  • 为了避免子类安全问题,依赖于状态的类应该要么将其等待和通知协议完全公开到子类,要么防止子类参与到影响协议的过程中
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容