1   /**
2    * Copyright 2008 Atlassian Pty Ltd 
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License"); 
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at 
7    * 
8    *     http://www.apache.org/licenses/LICENSE-2.0 
9    * 
10   * Unless required by applicable law or agreed to in writing, software 
11   * distributed under the License is distributed on an "AS IS" BASIS, 
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
13   * See the License for the specific language governing permissions and 
14   * limitations under the License.
15   */
16  
17  package com.atlassian.util.concurrent;
18  
19  import java.util.concurrent.atomic.AtomicInteger;
20  
21  /**
22   * Simple Latch-like structure where threads jump in a queue and are let off rally-style, one after
23   * the other.
24   */
25  interface LatchQueue {
26      /**
27       * await until a {@link #release()} is called
28       */
29      void await();
30  
31      /**
32       * cause any threads backed up in {@link #await()} to go
33       */
34      void release();
35  
36      /**
37       * How many threads are waiting.
38       * 
39       * @return the number of threads waiting.
40       */
41      int size();
42  
43      class SinglePass implements LatchQueue {
44          private final BooleanLatch latch = new BooleanLatch();
45          private final AtomicInteger count = new AtomicInteger();
46  
47          /**
48           * Construct a new SinglePass LatchQueue, optionally with the first call to not wait by
49           * releasing the latch.
50           * 
51           * @param prep if you want the first call to await to get a latch.
52           */
53          SinglePass(final boolean prep) {
54              if (prep) {
55                  latch.release();
56              }
57          }
58  
59          public void await() {
60              try {
61                  count.incrementAndGet();
62                  latch.await();
63              }
64              catch (final InterruptedException e) {
65                  throw new RuntimeInterruptedException(e);
66              }
67              finally {
68                  count.decrementAndGet();
69              }
70          }
71  
72          public void release() {
73              latch.release();
74          }
75  
76          public int size() {
77              return count.get();
78          }
79      }
80  }