File: SynchronousChannel.java

package info (click to toggle)
concurrent-dfsg 1.3.4-4
  • links: PTS, VCS
  • area: main
  • in suites: buster, jessie, jessie-kfreebsd, squeeze, stretch, wheezy
  • size: 976 kB
  • ctags: 2,018
  • sloc: java: 10,704; xml: 49; makefile: 12
file content (375 lines) | stat: -rw-r--r-- 10,494 bytes parent folder | download | duplicates (3)
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
/*
  File: SynchronousChannel.java

  Originally written by Doug Lea and released into the public domain.
  This may be used for any purposes whatsoever without acknowledgment.
  Thanks for the assistance and support of Sun Microsystems Labs,
  and everyone contributing, testing, and using this code.

  History:
  Date       Who                What
  11Jun1998  dl               Create public version
  17Jul1998  dl               Disabled direct semaphore permit check
  31Jul1998  dl               Replaced main algorithm with one with
                              better scaling and fairness properties.
  25aug1998  dl               added peek
  24Nov2001  dl               Replaced main algorithm with faster one.
*/

package EDU.oswego.cs.dl.util.concurrent;

/**
 * A rendezvous channel, similar to those used in CSP and Ada.  Each
 * put must wait for a take, and vice versa.  Synchronous channels
 * are well suited for handoff designs, in which an object running in
 * one thread must synch up with an object running in another thread
 * in order to hand it some information, event, or task. 
 * <p> If you only need threads to synch up without
 * exchanging information, consider using a Barrier. If you need
 * bidirectional exchanges, consider using a Rendezvous.  <p>
 *
 * <p>[<a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>]
 * @see CyclicBarrier
 * @see Rendezvous
**/

public class SynchronousChannel implements BoundedChannel {

  /*
    This implementation divides actions into two cases for puts:

    * An arriving putter that does not already have a waiting taker 
      creates a node holding item, and then waits for a taker to take it.
    * An arriving putter that does already have a waiting taker fills
      the slot node created by the taker, and notifies it to continue.

   And symmetrically, two for takes:

    * An arriving taker that does not already have a waiting putter
      creates an empty slot node, and then waits for a putter to fill it.
    * An arriving taker that does already have a waiting putter takes
      item from the node created by the putter, and notifies it to continue.

   This requires keeping two simple queues: waitingPuts and waitingTakes.
   
   When a put or take waiting for the actions of its counterpart
   aborts due to interruption or timeout, it marks the node
   it created as "CANCELLED", which causes its counterpart to retry
   the entire put or take sequence.
  */

  /** 
   * Special marker used in queue nodes to indicate that
   * the thread waiting for a change in the node has timed out
   * or been interrupted.
   **/
  protected static final Object CANCELLED = new Object();
  
  /**
   * Simple FIFO queue class to hold waiting puts/takes.
   **/
  protected static class Queue {
    protected LinkedNode head;
    protected LinkedNode last;

    protected void enq(LinkedNode p) { 
      if (last == null) 
        last = head = p;
      else 
        last = last.next = p;
    }

    protected LinkedNode deq() {
      LinkedNode p = head;
      if (p != null && (head = p.next) == null) 
        last = null;
      return p;
    }
  }

  protected final Queue waitingPuts = new Queue();
  protected final Queue waitingTakes = new Queue();

  /**
   * @return zero --
   * Synchronous channels have no internal capacity.
   **/
  public int capacity() { return 0; }

  /**
   * @return null --
   * Synchronous channels do not hold contents unless actively taken
   **/
  public Object peek() {  return null;  }


  public void put(Object x) throws InterruptedException {
    if (x == null) throw new IllegalArgumentException();

    // This code is conceptually straightforward, but messy
    // because we need to intertwine handling of put-arrives first
    // vs take-arrives first cases.

    // Outer loop is to handle retry due to cancelled waiting taker
    for (;;) { 

      // Get out now if we are interrupted
      if (Thread.interrupted()) throw new InterruptedException();

      // Exactly one of item or slot will be nonnull at end of
      // synchronized block, depending on whether a put or a take
      // arrived first. 
      LinkedNode slot;
      LinkedNode item = null;

      synchronized(this) {
        // Try to match up with a waiting taker; fill and signal it below
        slot = waitingTakes.deq();

        // If no takers yet, create a node and wait below
        if (slot == null) 
          waitingPuts.enq(item = new LinkedNode(x));
      }

      if (slot != null) { // There is a waiting taker.
        // Fill in the slot created by the taker and signal taker to
        // continue.
        synchronized(slot) {
          if (slot.value != CANCELLED) {
            slot.value = x;
            slot.notify();
            return;
          }
          // else the taker has cancelled, so retry outer loop
        }
      }

      else { 
        // Wait for a taker to arrive and take the item.
        synchronized(item) {
          try {
            while (item.value != null)
              item.wait();
            return;
          }
          catch (InterruptedException ie) {
            // If item was taken, return normally but set interrupt status
            if (item.value == null) {
              Thread.currentThread().interrupt();
              return;
            }
            else {
              item.value = CANCELLED;
              throw ie;
            }
          }
        }
      }
    }
  }

  public Object take() throws InterruptedException {
    // Entirely symmetric to put()

    for (;;) {
      if (Thread.interrupted()) throw new InterruptedException();

      LinkedNode item;
      LinkedNode slot = null;

      synchronized(this) {
        item = waitingPuts.deq();
        if (item == null) 
          waitingTakes.enq(slot = new LinkedNode());
      }

      if (item != null) {
        synchronized(item) {
          Object x = item.value;
          if (x != CANCELLED) {
            item.value = null;
            item.next = null;
            item.notify();
            return x;
          }
        }
      }

      else {
        synchronized(slot) {
          try {
            for (;;) {
              Object x = slot.value;
              if (x != null) {
                slot.value = null;
                slot.next = null;
                return x;
              }
              else
                slot.wait();
            }
          }
          catch(InterruptedException ie) {
            Object x = slot.value;
            if (x != null) {
              slot.value = null;
              slot.next = null;
              Thread.currentThread().interrupt();
              return x;
            }
            else {
              slot.value = CANCELLED;
              throw ie;
            }
          }
        }
      }
    }
  }

  /*
    Offer and poll are just like put and take, except even messier.
   */


  public boolean offer(Object x, long msecs) throws InterruptedException {
    if (x == null) throw new IllegalArgumentException();
    long waitTime = msecs;
    long startTime = 0; // lazily initialize below if needed
    
    for (;;) {
      if (Thread.interrupted()) throw new InterruptedException();

      LinkedNode slot;
      LinkedNode item = null;

      synchronized(this) {
        slot = waitingTakes.deq();
        if (slot == null) {
          if (waitTime <= 0) 
            return false;
          else 
            waitingPuts.enq(item = new LinkedNode(x));
        }
      }

      if (slot != null) {
        synchronized(slot) {
          if (slot.value != CANCELLED) {
            slot.value = x;
            slot.notify();
            return true;
          }
        }
      }

      long now = System.currentTimeMillis();
      if (startTime == 0) 
        startTime = now;
      else 
        waitTime = msecs - (now - startTime);

      if (item != null) {
        synchronized(item) {
          try {
            for (;;) {
              if (item.value == null) 
                return true;
              if (waitTime <= 0) {
                item.value = CANCELLED;
                return false;
              }
              item.wait(waitTime);
              waitTime = msecs - (System.currentTimeMillis() - startTime);
            }
          }
          catch (InterruptedException ie) {
            if (item.value == null) {
              Thread.currentThread().interrupt();
              return true;
            }
            else {
              item.value = CANCELLED;
              throw ie;
            }
          }
        }
      }
    }
  }

  public Object poll(long msecs) throws InterruptedException {
    long waitTime = msecs;
    long startTime = 0;

    for (;;) {
      if (Thread.interrupted()) throw new InterruptedException();

      LinkedNode item;
      LinkedNode slot = null;

      synchronized(this) {
        item = waitingPuts.deq();
        if (item == null) {
          if (waitTime <= 0) 
            return null;
          else 
            waitingTakes.enq(slot = new LinkedNode());
        }
      }

      if (item != null) {
        synchronized(item) {
          Object x = item.value;
          if (x != CANCELLED) {
            item.value = null;
            item.next = null;
            item.notify();
            return x;
          }
        }
      }

      long now = System.currentTimeMillis();
      if (startTime == 0) 
        startTime = now;
      else 
        waitTime = msecs - (now - startTime);

      if (slot != null) {
        synchronized(slot) {
          try {
            for (;;) {
              Object x = slot.value;
              if (x != null) {
                slot.value = null;
                slot.next = null;
                return x;
              }
              if (waitTime <= 0) {
                slot.value = CANCELLED;
                return null;
              }
              slot.wait(waitTime);
              waitTime = msecs - (System.currentTimeMillis() - startTime);
            }
          }
          catch(InterruptedException ie) {
            Object x = slot.value;
            if (x != null) {
              slot.value = null;
              slot.next = null;
              Thread.currentThread().interrupt();
              return x;
            }
            else {
              slot.value = CANCELLED;
              throw ie;
            }
          }
        }
      }
    }
  }

}