Exchanger

说说 Exchanger 原理

Exchanger 是在两个任务之间交换对象的栅栏。当一个任务进入栅栏,它就拥有一个对象,当该任务离开栅栏,原来拥有的对象将被另外的任务持有。

应用场景

通常用于一个任务创建对象(创建该对象的代价比较大),其他任务来消费该对象。通过这种方式,更多的这样的对象可以同时创建,消费。 《Thinking in Java》

源码注释

A synchronization point at which threads can pair and swap elements
within pairs. Each thread presents some object on entry to the
{@link #exchange exchange} method, matches with a partner thread,
and receives its partner’s object on return. An Exchanger may be
viewed as a bidirectional form of a {@link SynchronousQueue}.
Exchangers may be useful in applications such as genetic algorithms
and pipeline designs.
一个同步节点,在这个节点上成对的线程可以结对和相互交换元素。每个线程都可以贡献
一些对象在进入exchange方法时,与结伴的线程相匹配,并且接受它的结伴线程的对象在返回时。
Exchanger可以看做SynchronousQueue的双向的格式。Exchangers 在生成算法和管道设计中是有用的。

Sample Usage:
Here are the highlights of a class that uses an {@code Exchanger}
to swap buffers between threads so that the thread filling the
buffer gets a freshly emptied one when it needs it, handing off the
filled one to the thread emptying the buffer.

简单实用: 这里的类的集合实用Exchanger在线程之间交换数据,这样缓存已满的线程将得到一个
新的空的缓存,切换已经满的缓存到那个缓存为空的线程中。

“`
class FillAndEmpty {
Exchanger exchanger = new Exchanger();
DataBuffer initialEmptyBuffer = … a made-up type
DataBuffer initialFullBuffer = …

class FillingLoop implements Runnable {
  public void run() {
    DataBuffer currentBuffer = initialEmptyBuffer;
    try {
      while (currentBuffer != null) {
        addToBuffer(currentBuffer);
        if (currentBuffer.isFull())
          currentBuffer = exchanger.exchange(currentBuffer);
      }
    } catch (InterruptedException ex) { ... handle ... }
  }
}

class EmptyingLoop implements Runnable {
  public void run() {
    DataBuffer currentBuffer = initialFullBuffer;
    try {
      while (currentBuffer != null) {
        takeFromBuffer(currentBuffer);
        if (currentBuffer.isEmpty())
          currentBuffer = exchanger.exchange(currentBuffer);
      }
    } catch (InterruptedException ex) { ... handle ...}
  }
}

void start() {
  new Thread(new FillingLoop()).start();
  new Thread(new EmptyingLoop()).start();
}           }}

“`

Memory consistency effects: For each pair of threads that
successfully exchange objects via an {@code Exchanger}, actions
prior to the {@code exchange()} in each thread
happen-before
those subsequent to a return from the corresponding {@code exchange()}
in the other thread.

内存一致性影响:每对通过Exchanger交换对象的线程,在exchange()方法前操作。
随后从另外的线程的exchange()方法返回。

@since 1.5
@author Doug Lea and Bill Scherer and Michael Scott
@param The type of objects that may be exchanged

#### exchange()方法注释内容

Waits for another thread to arrive at this exchange point (unless
the current thread is {@linkplain Thread#interrupt interrupted}),
and then transfers the given object to it, receiving its object
in return.

If another thread is already waiting at the exchange point then it is resumed for thread scheduling purposes and receives the object passed in by the current thread. The current thread returns immediately, receiving the object passed to the exchange by that other thread.

If no other thread is already waiting at the exchange then the current thread is disabled for thread scheduling purposes and lies dormant until one of two things happens:

  • Some other thread enters the exchange; or
  • Some other thread {@linkplain Thread#interrupt interrupts} the current thread.

If the current thread:

  • has its interrupted status set on entry to this method; or
  • is {@linkplain Thread#interrupt interrupted} while waiting for the exchange,
then {@link InterruptedException} is thrown and the current thread’s interrupted status is cleared. @param x the object to exchange @return the object provided by the other thread @throws InterruptedException if the current thread was interrupted while waiting

@SuppressWarnings("unchecked")
    public V exchange(V x) throws InterruptedException {
        Object v;
        Object item = (x == null) ? NULL_ITEM : x; // translate null args
        if ((arena != null ||
             (v = slotExchange(item, false, 0L)) == null) &&
            ((Thread.interrupted() || // disambiguates null return
              (v = arenaExchange(item, false, 0L)) == null)))
            throw new InterruptedException();
        return (v == NULL_ITEM) ? null : (V)v;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值