12
|
1 package jp.ac.u_ryukyu.treevnc;
|
3
|
2
|
74
|
3 import java.nio.ByteBuffer;
|
3
|
4 import java.util.concurrent.CountDownLatch;
|
|
5
|
|
6 public class MulticastQueue<T>
|
|
7 {
|
|
8
|
|
9 Node<T> tail;
|
|
10
|
|
11 public MulticastQueue()
|
|
12 {
|
|
13 tail = new Node<T>(null);
|
|
14 }
|
74
|
15
|
|
16 /**
|
|
17 * @param size
|
|
18 * @return
|
|
19 *
|
|
20 * try to allocate byteBuffer.
|
|
21 * wait until heap is available.
|
|
22 *
|
|
23 *
|
|
24 */
|
|
25 public ByteBuffer allocate(int size)
|
|
26 {
|
|
27 ByteBuffer b=null;
|
|
28 while(true){
|
76
|
29 try {
|
74
|
30 b = ByteBuffer.allocate(size);
|
76
|
31 } catch (OutOfMemoryError e) {
|
|
32 b = null;
|
|
33 System.err.println("multicastqueue : wait for heap : " + e);
|
74
|
34 }
|
76
|
35 if (b!=null) {
|
74
|
36 break;
|
|
37 }
|
|
38 try {
|
|
39 wait();
|
|
40 } catch (InterruptedException e) {
|
|
41 }
|
|
42 }
|
|
43 return b;
|
|
44 }
|
3
|
45
|
74
|
46 public synchronized void heapAvailable() {
|
|
47 notifyAll();
|
|
48 }
|
|
49
|
3
|
50 public synchronized void put(T item)
|
|
51 {
|
|
52 Node<T> next = new Node<T>(item);
|
|
53 tail.set(next);
|
|
54 tail = next;
|
|
55 }
|
|
56
|
|
57 public Client<T> newClient()
|
|
58 {
|
|
59 return new Client<T>(tail);
|
|
60 }
|
|
61
|
4
|
62 public static class Client<T>
|
3
|
63 {
|
|
64 Node<T> node;
|
|
65
|
|
66 Client(Node<T> tail)
|
|
67 {
|
|
68 node = tail;
|
|
69 }
|
|
70
|
|
71 synchronized public T poll()
|
|
72 {
|
|
73 Node<T> next = null;
|
|
74 T item = null;
|
|
75 do {
|
|
76 try {
|
|
77 next = node.next();
|
|
78 }catch(InterruptedException _e){
|
|
79 continue;
|
|
80 }
|
|
81 item = next.getItem();
|
|
82 node = next;
|
|
83 } while ( item == null);
|
|
84 return item;
|
|
85 }
|
|
86 }
|
|
87
|
|
88 static class Node<T>
|
|
89 {
|
|
90 private T item;
|
|
91 private Node<T> next;
|
|
92 private CountDownLatch latch;
|
|
93
|
|
94 public Node(T item)
|
|
95 {
|
|
96 this.item = item;
|
|
97 this.next = null;
|
|
98 latch = new CountDownLatch(1);
|
|
99 }
|
|
100
|
|
101 synchronized public T getItem() {
|
|
102 return item;
|
|
103 }
|
|
104
|
|
105 public void set(Node<T> next)
|
|
106 {
|
|
107 this.next = next;
|
|
108 latch.countDown();
|
|
109 }
|
|
110
|
|
111 public Node<T> next() throws InterruptedException
|
|
112 {
|
|
113 latch.await();
|
|
114 return next;
|
|
115 }
|
|
116
|
|
117 synchronized public void clear() {
|
|
118 item = null;
|
|
119 }
|
|
120 }
|
|
121 }
|