1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| package cn.idea360.migrate;
import java.util.Collection; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock;
public class Channel {
private final int capacity;
private final int batchSize;
private final ArrayBlockingQueue<Object> queue;
private final ReentrantLock lock;
private final Condition notEmpty;
private final Condition notFull;
public Channel() { this.capacity = 100; this.batchSize = 10; this.queue = new ArrayBlockingQueue<>(capacity); this.lock = new ReentrantLock(); this.notFull = lock.newCondition(); this.notEmpty = lock.newCondition(); }
public void push(Object record) { try { this.queue.put(record); } catch (InterruptedException e) { Thread.currentThread().interrupt();; } }
public void pushAll(Collection<Object> records) { lock.lock(); try { while (records.size() > this.queue.remainingCapacity()) { notFull.await(200L, TimeUnit.MILLISECONDS); } this.queue.addAll(records); this.notEmpty.signalAll(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { lock.unlock(); } }
public Object pull() { try { return this.queue.take(); } catch (Exception e) { Thread.currentThread().interrupt(); throw new RuntimeException("pull err", e); } }
public void pullAll(Collection<Object> rs) { rs.clear(); lock.lock(); try { while (this.queue.drainTo(rs, batchSize) <= 0) { this.notEmpty.await(200, TimeUnit.MILLISECONDS); } this.notFull.signalAll(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { lock.unlock(); } } }
|