ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/SemaphoreTest.java
(Generate patch)

Comparing jsr166/src/test/tck/SemaphoreTest.java (file contents):
Revision 1.18 by jsr166, Mon Nov 16 05:58:01 2009 UTC vs.
Revision 1.29 by jsr166, Tue May 31 16:16:24 2011 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   * Other contributors include Andrew Wright, Jeffrey Hayes,
6   * Pat Fisher, Mike Judd.
7   */
8  
9   import junit.framework.*;
10   import java.util.*;
11 < import java.util.concurrent.*;
12 < import java.io.*;
11 > import java.util.concurrent.CountDownLatch;
12 > import java.util.concurrent.Semaphore;
13 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
14  
15   public class SemaphoreTest extends JSR166TestCase {
16      public static void main(String[] args) {
17 <        junit.textui.TestRunner.run (suite());
17 >        junit.textui.TestRunner.run(suite());
18      }
19      public static Test suite() {
20 <        return new TestSuite(SemaphoreTest.class);
20 >        return new TestSuite(SemaphoreTest.class);
21      }
22  
23      /**
24       * Subclass to expose protected methods
25       */
26      static class PublicSemaphore extends Semaphore {
27 <        PublicSemaphore(int p, boolean f) { super(p, f); }
27 >        PublicSemaphore(int permits) { super(permits); }
28 >        PublicSemaphore(int permits, boolean fair) { super(permits, fair); }
29          public Collection<Thread> getQueuedThreads() {
30              return super.getQueuedThreads();
31          }
32 <        public void reducePermits(int p) {
33 <            super.reducePermits(p);
32 >        public boolean hasQueuedThread(Thread t) {
33 >            return super.getQueuedThreads().contains(t);
34 >        }
35 >        public void reducePermits(int reduction) {
36 >            super.reducePermits(reduction);
37          }
38      }
39  
40      /**
41       * A runnable calling acquire
42       */
43 <    class InterruptibleLockRunnable implements Runnable {
43 >    class InterruptibleLockRunnable extends CheckedRunnable {
44          final Semaphore lock;
45 <        InterruptibleLockRunnable(Semaphore l) { lock = l; }
46 <        public void run() {
45 >        InterruptibleLockRunnable(Semaphore s) { lock = s; }
46 >        public void realRun() {
47              try {
48                  lock.acquire();
49 <            } catch (InterruptedException success) {}
49 >            }
50 >            catch (InterruptedException ignored) {}
51          }
52      }
53  
48
54      /**
55 <     * A runnable calling acquire that expects to be
51 <     * interrupted
55 >     * A runnable calling acquire that expects to be interrupted
56       */
57 <    class InterruptedLockRunnable implements Runnable {
57 >    class InterruptedLockRunnable extends CheckedInterruptedRunnable {
58          final Semaphore lock;
59 <        InterruptedLockRunnable(Semaphore l) { lock = l; }
60 <        public void run() {
61 <            try {
62 <                lock.acquire();
63 <                threadShouldThrow();
64 <            } catch (InterruptedException success) {}
59 >        InterruptedLockRunnable(Semaphore s) { lock = s; }
60 >        public void realRun() throws InterruptedException {
61 >            lock.acquire();
62 >        }
63 >    }
64 >
65 >    /**
66 >     * Spin-waits until s.hasQueuedThread(t) becomes true.
67 >     */
68 >    void waitForQueuedThread(PublicSemaphore s, Thread t) {
69 >        long startTime = System.nanoTime();
70 >        while (!s.hasQueuedThread(t)) {
71 >            if (millisElapsedSince(startTime) > LONG_DELAY_MS)
72 >                throw new AssertionFailedError("timed out");
73 >            Thread.yield();
74 >        }
75 >        assert(s.hasQueuedThreads());
76 >        assertTrue(t.isAlive());
77 >    }
78 >
79 >    /**
80 >     * Spin-waits until s.hasQueuedThreads() becomes true.
81 >     */
82 >    void waitForQueuedThreads(Semaphore s) {
83 >        long startTime = System.nanoTime();
84 >        while (!s.hasQueuedThreads()) {
85 >            if (millisElapsedSince(startTime) > LONG_DELAY_MS)
86 >                throw new AssertionFailedError("timed out");
87 >            Thread.yield();
88 >        }
89 >    }
90 >
91 >    enum AcquireMethod {
92 >        acquire() {
93 >            void acquire(Semaphore s) throws InterruptedException {
94 >                s.acquire();
95 >            }
96 >        },
97 >        acquireN() {
98 >            void acquire(Semaphore s, int permits) throws InterruptedException {
99 >                s.acquire(permits);
100 >            }
101 >        },
102 >        acquireUninterruptibly() {
103 >            void acquire(Semaphore s) {
104 >                s.acquireUninterruptibly();
105 >            }
106 >        },
107 >        acquireUninterruptiblyN() {
108 >            void acquire(Semaphore s, int permits) {
109 >                s.acquireUninterruptibly(permits);
110 >            }
111 >        },
112 >        tryAcquire() {
113 >            void acquire(Semaphore s) {
114 >                assertTrue(s.tryAcquire());
115 >            }
116 >        },
117 >        tryAcquireN() {
118 >            void acquire(Semaphore s, int permits) {
119 >                assertTrue(s.tryAcquire(permits));
120 >            }
121 >        },
122 >        tryAcquireTimed() {
123 >            void acquire(Semaphore s) throws InterruptedException {
124 >                assertTrue(s.tryAcquire(2 * LONG_DELAY_MS, MILLISECONDS));
125 >            }
126 >        },
127 >        tryAcquireTimedN {
128 >            void acquire(Semaphore s, int permits) throws InterruptedException {
129 >                assertTrue(s.tryAcquire(permits, 2 * LONG_DELAY_MS, MILLISECONDS));
130 >            }
131 >        };
132 >
133 >        // Intentionally meta-circular
134 >
135 >        /** Acquires 1 permit. */
136 >        void acquire(Semaphore s) throws InterruptedException {
137 >            acquire(s, 1);
138 >        }
139 >        /** Acquires the given number of permits. */
140 >        void acquire(Semaphore s, int permits) throws InterruptedException {
141 >            for (int i = 0; i < permits; i++)
142 >                acquire(s);
143          }
144      }
145  
146      /**
147       * Zero, negative, and positive initial values are allowed in constructor
148       */
149 <    public void testConstructor() {
150 <        Semaphore s0 = new Semaphore(0, false);
151 <        assertEquals(0, s0.availablePermits());
152 <        assertFalse(s0.isFair());
153 <        Semaphore s1 = new Semaphore(-1, false);
154 <        assertEquals(-1, s1.availablePermits());
155 <        assertFalse(s1.isFair());
156 <        Semaphore s2 = new Semaphore(-1, false);
75 <        assertEquals(-1, s2.availablePermits());
76 <        assertFalse(s2.isFair());
149 >    public void testConstructor()      { testConstructor(false); }
150 >    public void testConstructor_fair() { testConstructor(true); }
151 >    public void testConstructor(boolean fair) {
152 >        for (int permits : new int[] { -42, -1, 0, 1, 42 }) {
153 >            Semaphore s = new Semaphore(permits, fair);
154 >            assertEquals(permits, s.availablePermits());
155 >            assertEquals(fair, s.isFair());
156 >        }
157      }
158  
159      /**
160       * Constructor without fairness argument behaves as nonfair
161       */
162 <    public void testConstructor2() {
163 <        Semaphore s0 = new Semaphore(0);
164 <        assertEquals(0, s0.availablePermits());
165 <        assertFalse(s0.isFair());
166 <        Semaphore s1 = new Semaphore(-1);
167 <        assertEquals(-1, s1.availablePermits());
88 <        assertFalse(s1.isFair());
89 <        Semaphore s2 = new Semaphore(-1);
90 <        assertEquals(-1, s2.availablePermits());
91 <        assertFalse(s2.isFair());
162 >    public void testConstructorDefaultsToNonFair() {
163 >        for (int permits : new int[] { -42, -1, 0, 1, 42 }) {
164 >            Semaphore s = new Semaphore(permits);
165 >            assertEquals(permits, s.availablePermits());
166 >            assertFalse(s.isFair());
167 >        }
168      }
169  
170      /**
171       * tryAcquire succeeds when sufficient permits, else fails
172       */
173 <    public void testTryAcquireInSameThread() {
174 <        Semaphore s = new Semaphore(2, false);
173 >    public void testTryAcquireInSameThread()      { testTryAcquireInSameThread(false); }
174 >    public void testTryAcquireInSameThread_fair() { testTryAcquireInSameThread(true); }
175 >    public void testTryAcquireInSameThread(boolean fair) {
176 >        Semaphore s = new Semaphore(2, fair);
177          assertEquals(2, s.availablePermits());
178          assertTrue(s.tryAcquire());
179          assertTrue(s.tryAcquire());
180          assertEquals(0, s.availablePermits());
181          assertFalse(s.tryAcquire());
182 +        assertFalse(s.tryAcquire());
183 +        assertEquals(0, s.availablePermits());
184      }
185  
186      /**
187 <     * Acquire and release of semaphore succeed if initially available
108 <     */
109 <    public void testAcquireReleaseInSameThread() {
110 <        Semaphore s = new Semaphore(1, false);
111 <        try {
112 <            s.acquire();
113 <            s.release();
114 <            s.acquire();
115 <            s.release();
116 <            s.acquire();
117 <            s.release();
118 <            s.acquire();
119 <            s.release();
120 <            s.acquire();
121 <            s.release();
122 <            assertEquals(1, s.availablePermits());
123 <        } catch (InterruptedException e) {
124 <            unexpectedException();
125 <        }
126 <    }
127 <
128 <    /**
129 <     * Uninterruptible acquire and release of semaphore succeed if
130 <     * initially available
131 <     */
132 <    public void testAcquireUninterruptiblyReleaseInSameThread() {
133 <        Semaphore s = new Semaphore(1, false);
134 <        try {
135 <            s.acquireUninterruptibly();
136 <            s.release();
137 <            s.acquireUninterruptibly();
138 <            s.release();
139 <            s.acquireUninterruptibly();
140 <            s.release();
141 <            s.acquireUninterruptibly();
142 <            s.release();
143 <            s.acquireUninterruptibly();
144 <            s.release();
145 <            assertEquals(1, s.availablePermits());
146 <        } finally {
147 <        }
148 <    }
149 <
150 <    /**
151 <     * Timed Acquire and release of semaphore succeed if
152 <     * initially available
153 <     */
154 <    public void testTimedAcquireReleaseInSameThread() {
155 <        Semaphore s = new Semaphore(1, false);
156 <        try {
157 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
158 <            s.release();
159 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
160 <            s.release();
161 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
162 <            s.release();
163 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
164 <            s.release();
165 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
166 <            s.release();
167 <            assertEquals(1, s.availablePermits());
168 <        } catch (InterruptedException e) {
169 <            unexpectedException();
170 <        }
171 <    }
172 <
173 <    /**
174 <     * A release in one thread enables an acquire in another thread
175 <     */
176 <    public void testAcquireReleaseInDifferentThreads() {
177 <        final Semaphore s = new Semaphore(0, false);
178 <        Thread t = new Thread(new Runnable() {
179 <                public void run() {
180 <                    try {
181 <                        s.acquire();
182 <                        s.release();
183 <                        s.release();
184 <                        s.acquire();
185 <                    } catch (InterruptedException ie) {
186 <                        threadUnexpectedException();
187 <                    }
188 <                }
189 <            });
190 <        try {
191 <            t.start();
192 <            Thread.sleep(SHORT_DELAY_MS);
193 <            s.release();
194 <            s.release();
195 <            s.acquire();
196 <            s.acquire();
197 <            s.release();
198 <            t.join();
199 <        } catch (InterruptedException e) {
200 <            unexpectedException();
201 <        }
202 <    }
203 <
204 <    /**
205 <     * A release in one thread enables an uninterruptible acquire in another thread
187 >     * timed tryAcquire times out
188       */
189 <    public void testUninterruptibleAcquireReleaseInDifferentThreads() {
190 <        final Semaphore s = new Semaphore(0, false);
191 <        Thread t = new Thread(new Runnable() {
192 <                public void run() {
193 <                    s.acquireUninterruptibly();
194 <                    s.release();
195 <                    s.release();
196 <                    s.acquireUninterruptibly();
197 <                }
198 <            });
199 <        try {
200 <            t.start();
201 <            Thread.sleep(SHORT_DELAY_MS);
202 <            s.release();
203 <            s.release();
204 <            s.acquireUninterruptibly();
205 <            s.acquireUninterruptibly();
206 <            s.release();
207 <            t.join();
208 <        } catch (InterruptedException e) {
209 <            unexpectedException();
210 <        }
211 <    }
189 >    public void testTryAcquire_timeout()      { testTryAcquire_timeout(false); }
190 >    public void testTryAcquire_timeout_fair() { testTryAcquire_timeout(true); }
191 >    public void testTryAcquire_timeout(boolean fair) {
192 >        Semaphore s = new Semaphore(0, fair);
193 >        long startTime = System.nanoTime();
194 >        try { assertFalse(s.tryAcquire(timeoutMillis(), MILLISECONDS)); }
195 >        catch (InterruptedException e) { threadUnexpectedException(e); }
196 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
197 >    }
198 >
199 >    /**
200 >     * timed tryAcquire(N) times out
201 >     */
202 >    public void testTryAcquireN_timeout()      { testTryAcquireN_timeout(false); }
203 >    public void testTryAcquireN_timeout_fair() { testTryAcquireN_timeout(true); }
204 >    public void testTryAcquireN_timeout(boolean fair) {
205 >        Semaphore s = new Semaphore(2, fair);
206 >        long startTime = System.nanoTime();
207 >        try { assertFalse(s.tryAcquire(3, timeoutMillis(), MILLISECONDS)); }
208 >        catch (InterruptedException e) { threadUnexpectedException(e); }
209 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
210 >    }
211 >
212 >    /**
213 >     * acquire(), acquire(N), timed tryAcquired, timed tryAcquire(N)
214 >     * are interruptible
215 >     */
216 >    public void testInterruptible_acquire()               { testInterruptible(false, AcquireMethod.acquire); }
217 >    public void testInterruptible_acquire_fair()          { testInterruptible(true,  AcquireMethod.acquire); }
218 >    public void testInterruptible_acquireN()              { testInterruptible(false, AcquireMethod.acquireN); }
219 >    public void testInterruptible_acquireN_fair()         { testInterruptible(true,  AcquireMethod.acquireN); }
220 >    public void testInterruptible_tryAcquireTimed()       { testInterruptible(false, AcquireMethod.tryAcquireTimed); }
221 >    public void testInterruptible_tryAcquireTimed_fair()  { testInterruptible(true,  AcquireMethod.tryAcquireTimed); }
222 >    public void testInterruptible_tryAcquireTimedN()      { testInterruptible(false, AcquireMethod.tryAcquireTimedN); }
223 >    public void testInterruptible_tryAcquireTimedN_fair() { testInterruptible(true,  AcquireMethod.tryAcquireTimedN); }
224 >    public void testInterruptible(boolean fair, final AcquireMethod acquirer) {
225 >        final PublicSemaphore s = new PublicSemaphore(0, fair);
226 >        final Semaphore anotherInterruptPlease = new Semaphore(0, fair);
227 >        Thread t = newStartedThread(new CheckedRunnable() {
228 >            public void realRun() {
229 >                // Interrupt before acquire
230 >                Thread.currentThread().interrupt();
231 >                try {
232 >                    acquirer.acquire(s);
233 >                    shouldThrow();
234 >                } catch (InterruptedException success) {}
235 >
236 >                // Interrupt during acquire
237 >                try {
238 >                    acquirer.acquire(s);
239 >                    shouldThrow();
240 >                } catch (InterruptedException success) {}
241 >
242 >                // Interrupt before acquire(N)
243 >                Thread.currentThread().interrupt();
244 >                try {
245 >                    acquirer.acquire(s, 3);
246 >                    shouldThrow();
247 >                } catch (InterruptedException success) {}
248 >
249 >                anotherInterruptPlease.release();
250 >
251 >                // Interrupt during acquire(N)
252 >                try {
253 >                    acquirer.acquire(s, 3);
254 >                    shouldThrow();
255 >                } catch (InterruptedException success) {}
256 >            }});
257 >
258 >        waitForQueuedThread(s, t);
259 >        t.interrupt();
260 >        try {
261 >            assertTrue(anotherInterruptPlease.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
262 >        } catch (InterruptedException e) { threadUnexpectedException(e); }
263 >        waitForQueuedThread(s, t);
264 >        t.interrupt();
265 >        awaitTermination(t);
266 >    }
267 >
268 >    /**
269 >     * acquireUninterruptibly(), acquireUninterruptibly(N) are
270 >     * uninterruptible
271 >     */
272 >    public void testUninterruptible_acquireUninterruptibly()       { testUninterruptible(false, AcquireMethod.acquireUninterruptibly); }
273 >    public void testUninterruptible_acquireUninterruptibly_fair()  { testUninterruptible(true,  AcquireMethod.acquireUninterruptibly); }
274 >    public void testUninterruptible_acquireUninterruptiblyN()      { testUninterruptible(false, AcquireMethod.acquireUninterruptiblyN); }
275 >    public void testUninterruptible_acquireUninterruptiblyN_fair() { testUninterruptible(true,  AcquireMethod.acquireUninterruptiblyN); }
276 >    public void testUninterruptible(boolean fair, final AcquireMethod acquirer) {
277 >        final PublicSemaphore s = new PublicSemaphore(0, fair);
278 >        final Semaphore anotherInterruptPlease = new Semaphore(0, fair);
279 >        Thread t = newStartedThread(new CheckedRunnable() {
280 >            public void realRun() throws InterruptedException {
281 >                // Interrupt before acquire
282 >                Thread.currentThread().interrupt();
283 >                acquirer.acquire(s);
284 >                assertTrue(Thread.interrupted());
285 >
286 >                anotherInterruptPlease.release();
287 >
288 >                // Interrupt during acquire
289 >                acquirer.acquire(s);
290 >                assertTrue(Thread.interrupted());
291 >            }});
292  
293 +        waitForQueuedThread(s, t);
294 +        assertThreadStaysAlive(t);
295 +        s.release();
296  
232    /**
233     *  A release in one thread enables a timed acquire in another thread
234     */
235    public void testTimedAcquireReleaseInDifferentThreads() {
236        final Semaphore s = new Semaphore(1, false);
237        Thread t = new Thread(new Runnable() {
238                public void run() {
239                    try {
240                        s.release();
241                        threadAssertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
242                        s.release();
243                        threadAssertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
244
245                    } catch (InterruptedException ie) {
246                        threadUnexpectedException();
247                    }
248                }
249            });
297          try {
298 <            t.start();
299 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
300 <            s.release();
301 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
302 <            s.release();
303 <            s.release();
257 <            t.join();
258 <        } catch (InterruptedException e) {
259 <            unexpectedException();
260 <        }
261 <    }
262 <
263 <    /**
264 <     * A waiting acquire blocks interruptibly
265 <     */
266 <    public void testAcquire_InterruptedException() {
267 <        final Semaphore s = new Semaphore(0, false);
268 <        Thread t = new Thread(new Runnable() {
269 <                public void run() {
270 <                    try {
271 <                        s.acquire();
272 <                        threadShouldThrow();
273 <                    } catch (InterruptedException success) {}
274 <                }
275 <            });
276 <        t.start();
277 <        try {
278 <            Thread.sleep(SHORT_DELAY_MS);
279 <            t.interrupt();
280 <            t.join();
281 <        } catch (InterruptedException e) {
282 <            unexpectedException();
283 <        }
284 <    }
298 >            assertTrue(anotherInterruptPlease.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
299 >        } catch (InterruptedException e) { threadUnexpectedException(e); }
300 >        waitForQueuedThread(s, t);
301 >        t.interrupt();
302 >        assertThreadStaysAlive(t);
303 >        s.release();
304  
305 <    /**
287 <     *  A waiting timed acquire blocks interruptibly
288 <     */
289 <    public void testTryAcquire_InterruptedException() {
290 <        final Semaphore s = new Semaphore(0, false);
291 <        Thread t = new Thread(new Runnable() {
292 <                public void run() {
293 <                    try {
294 <                        s.tryAcquire(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
295 <                        threadShouldThrow();
296 <                    } catch (InterruptedException success) {
297 <                    }
298 <                }
299 <            });
300 <        t.start();
301 <        try {
302 <            Thread.sleep(SHORT_DELAY_MS);
303 <            t.interrupt();
304 <            t.join();
305 <        } catch (InterruptedException e) {
306 <            unexpectedException();
307 <        }
305 >        awaitTermination(t);
306      }
307  
308      /**
309       * hasQueuedThreads reports whether there are waiting threads
310       */
311 <    public void testHasQueuedThreads() {
312 <        final Semaphore lock = new Semaphore(1, false);
313 <        Thread t1 = new Thread(new InterruptedLockRunnable(lock));
314 <        Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
315 <        try {
316 <            assertFalse(lock.hasQueuedThreads());
317 <            lock.acquireUninterruptibly();
318 <            t1.start();
319 <            Thread.sleep(SHORT_DELAY_MS);
320 <            assertTrue(lock.hasQueuedThreads());
321 <            t2.start();
322 <            Thread.sleep(SHORT_DELAY_MS);
323 <            assertTrue(lock.hasQueuedThreads());
324 <            t1.interrupt();
325 <            Thread.sleep(SHORT_DELAY_MS);
326 <            assertTrue(lock.hasQueuedThreads());
327 <            lock.release();
328 <            Thread.sleep(SHORT_DELAY_MS);
331 <            assertFalse(lock.hasQueuedThreads());
332 <            t1.join();
333 <            t2.join();
334 <        } catch (Exception e) {
335 <            unexpectedException();
336 <        }
311 >    public void testHasQueuedThreads()      { testHasQueuedThreads(false); }
312 >    public void testHasQueuedThreads_fair() { testHasQueuedThreads(true); }
313 >    public void testHasQueuedThreads(boolean fair) {
314 >        final PublicSemaphore lock = new PublicSemaphore(1, fair);
315 >        assertFalse(lock.hasQueuedThreads());
316 >        lock.acquireUninterruptibly();
317 >        Thread t1 = newStartedThread(new InterruptedLockRunnable(lock));
318 >        waitForQueuedThread(lock, t1);
319 >        assertTrue(lock.hasQueuedThreads());
320 >        Thread t2 = newStartedThread(new InterruptibleLockRunnable(lock));
321 >        waitForQueuedThread(lock, t2);
322 >        assertTrue(lock.hasQueuedThreads());
323 >        t1.interrupt();
324 >        awaitTermination(t1);
325 >        assertTrue(lock.hasQueuedThreads());
326 >        lock.release();
327 >        awaitTermination(t2);
328 >        assertFalse(lock.hasQueuedThreads());
329      }
330  
331      /**
332       * getQueueLength reports number of waiting threads
333       */
334 <    public void testGetQueueLength() {
335 <        final Semaphore lock = new Semaphore(1, false);
336 <        Thread t1 = new Thread(new InterruptedLockRunnable(lock));
337 <        Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
338 <        try {
339 <            assertEquals(0, lock.getQueueLength());
340 <            lock.acquireUninterruptibly();
341 <            t1.start();
342 <            Thread.sleep(SHORT_DELAY_MS);
343 <            assertEquals(1, lock.getQueueLength());
344 <            t2.start();
345 <            Thread.sleep(SHORT_DELAY_MS);
346 <            assertEquals(2, lock.getQueueLength());
347 <            t1.interrupt();
348 <            Thread.sleep(SHORT_DELAY_MS);
349 <            assertEquals(1, lock.getQueueLength());
350 <            lock.release();
351 <            Thread.sleep(SHORT_DELAY_MS);
360 <            assertEquals(0, lock.getQueueLength());
361 <            t1.join();
362 <            t2.join();
363 <        } catch (Exception e) {
364 <            unexpectedException();
365 <        }
334 >    public void testGetQueueLength()      { testGetQueueLength(false); }
335 >    public void testGetQueueLength_fair() { testGetQueueLength(true); }
336 >    public void testGetQueueLength(boolean fair) {
337 >        final PublicSemaphore lock = new PublicSemaphore(1, fair);
338 >        assertEquals(0, lock.getQueueLength());
339 >        lock.acquireUninterruptibly();
340 >        Thread t1 = newStartedThread(new InterruptedLockRunnable(lock));
341 >        waitForQueuedThread(lock, t1);
342 >        assertEquals(1, lock.getQueueLength());
343 >        Thread t2 = newStartedThread(new InterruptibleLockRunnable(lock));
344 >        waitForQueuedThread(lock, t2);
345 >        assertEquals(2, lock.getQueueLength());
346 >        t1.interrupt();
347 >        awaitTermination(t1);
348 >        assertEquals(1, lock.getQueueLength());
349 >        lock.release();
350 >        awaitTermination(t2);
351 >        assertEquals(0, lock.getQueueLength());
352      }
353  
354      /**
355       * getQueuedThreads includes waiting threads
356       */
357 <    public void testGetQueuedThreads() {
358 <        final PublicSemaphore lock = new PublicSemaphore(1, false);
359 <        Thread t1 = new Thread(new InterruptedLockRunnable(lock));
360 <        Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
361 <        try {
362 <            assertTrue(lock.getQueuedThreads().isEmpty());
363 <            lock.acquireUninterruptibly();
364 <            assertTrue(lock.getQueuedThreads().isEmpty());
365 <            t1.start();
366 <            Thread.sleep(SHORT_DELAY_MS);
367 <            assertTrue(lock.getQueuedThreads().contains(t1));
368 <            t2.start();
369 <            Thread.sleep(SHORT_DELAY_MS);
370 <            assertTrue(lock.getQueuedThreads().contains(t1));
371 <            assertTrue(lock.getQueuedThreads().contains(t2));
372 <            t1.interrupt();
373 <            Thread.sleep(SHORT_DELAY_MS);
374 <            assertFalse(lock.getQueuedThreads().contains(t1));
375 <            assertTrue(lock.getQueuedThreads().contains(t2));
376 <            lock.release();
377 <            Thread.sleep(SHORT_DELAY_MS);
392 <            assertTrue(lock.getQueuedThreads().isEmpty());
393 <            t1.join();
394 <            t2.join();
395 <        } catch (Exception e) {
396 <            unexpectedException();
397 <        }
357 >    public void testGetQueuedThreads()      { testGetQueuedThreads(false); }
358 >    public void testGetQueuedThreads_fair() { testGetQueuedThreads(true); }
359 >    public void testGetQueuedThreads(boolean fair) {
360 >        final PublicSemaphore lock = new PublicSemaphore(1, fair);
361 >        assertTrue(lock.getQueuedThreads().isEmpty());
362 >        lock.acquireUninterruptibly();
363 >        assertTrue(lock.getQueuedThreads().isEmpty());
364 >        Thread t1 = newStartedThread(new InterruptedLockRunnable(lock));
365 >        waitForQueuedThread(lock, t1);
366 >        assertTrue(lock.getQueuedThreads().contains(t1));
367 >        Thread t2 = newStartedThread(new InterruptibleLockRunnable(lock));
368 >        waitForQueuedThread(lock, t2);
369 >        assertTrue(lock.getQueuedThreads().contains(t1));
370 >        assertTrue(lock.getQueuedThreads().contains(t2));
371 >        t1.interrupt();
372 >        awaitTermination(t1);
373 >        assertFalse(lock.getQueuedThreads().contains(t1));
374 >        assertTrue(lock.getQueuedThreads().contains(t2));
375 >        lock.release();
376 >        awaitTermination(t2);
377 >        assertTrue(lock.getQueuedThreads().isEmpty());
378      }
379  
380      /**
381       * drainPermits reports and removes given number of permits
382       */
383 <    public void testDrainPermits() {
384 <        Semaphore s = new Semaphore(0, false);
383 >    public void testDrainPermits()      { testDrainPermits(false); }
384 >    public void testDrainPermits_fair() { testDrainPermits(true); }
385 >    public void testDrainPermits(boolean fair) {
386 >        Semaphore s = new Semaphore(0, fair);
387          assertEquals(0, s.availablePermits());
388          assertEquals(0, s.drainPermits());
389          s.release(10);
# Line 412 | Line 394 | public class SemaphoreTest extends JSR16
394      }
395  
396      /**
397 <     * reducePermits reduces number of permits
397 >     * release(-N) throws IllegalArgumentException
398       */
399 <    public void testReducePermits() {
400 <        PublicSemaphore s = new PublicSemaphore(10, false);
401 <        assertEquals(10, s.availablePermits());
402 <        s.reducePermits(1);
421 <        assertEquals(9, s.availablePermits());
422 <        s.reducePermits(10);
423 <        assertEquals(-1, s.availablePermits());
424 <    }
425 <
426 <    /**
427 <     * a deserialized serialized semaphore has same number of permits
428 <     */
429 <    public void testSerialization() {
430 <        Semaphore l = new Semaphore(3, false);
399 >    public void testReleaseIAE()      { testReleaseIAE(false); }
400 >    public void testReleaseIAE_fair() { testReleaseIAE(true); }
401 >    public void testReleaseIAE(boolean fair) {
402 >        Semaphore s = new Semaphore(10, fair);
403          try {
404 <            l.acquire();
405 <            l.release();
406 <            ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
435 <            ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
436 <            out.writeObject(l);
437 <            out.close();
438 <
439 <            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
440 <            ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
441 <            Semaphore r = (Semaphore) in.readObject();
442 <            assertEquals(3, r.availablePermits());
443 <            assertFalse(r.isFair());
444 <            r.acquire();
445 <            r.release();
446 <        } catch (Exception e) {
447 <            unexpectedException();
448 <        }
404 >            s.release(-1);
405 >            shouldThrow();
406 >        } catch (IllegalArgumentException success) {}
407      }
408  
451
409      /**
410 <     * Zero, negative, and positive initial values are allowed in constructor
410 >     * reducePermits(-N) throws IllegalArgumentException
411       */
412 <    public void testConstructor_fair() {
413 <        Semaphore s0 = new Semaphore(0, true);
414 <        assertEquals(0, s0.availablePermits());
415 <        assertTrue(s0.isFair());
416 <        Semaphore s1 = new Semaphore(-1, true);
417 <        assertEquals(-1, s1.availablePermits());
418 <        Semaphore s2 = new Semaphore(-1, true);
419 <        assertEquals(-1, s2.availablePermits());
463 <    }
464 <
465 <    /**
466 <     * tryAcquire succeeds when sufficient permits, else fails
467 <     */
468 <    public void testTryAcquireInSameThread_fair() {
469 <        Semaphore s = new Semaphore(2, true);
470 <        assertEquals(2, s.availablePermits());
471 <        assertTrue(s.tryAcquire());
472 <        assertTrue(s.tryAcquire());
473 <        assertEquals(0, s.availablePermits());
474 <        assertFalse(s.tryAcquire());
412 >    public void testReducePermitsIAE()      { testReducePermitsIAE(false); }
413 >    public void testReducePermitsIAE_fair() { testReducePermitsIAE(true); }
414 >    public void testReducePermitsIAE(boolean fair) {
415 >        PublicSemaphore s = new PublicSemaphore(10, fair);
416 >        try {
417 >            s.reducePermits(-1);
418 >            shouldThrow();
419 >        } catch (IllegalArgumentException success) {}
420      }
421  
422      /**
423 <     * tryAcquire(n) succeeds when sufficient permits, else fails
423 >     * reducePermits reduces number of permits
424       */
425 <    public void testTryAcquireNInSameThread_fair() {
426 <        Semaphore s = new Semaphore(2, true);
427 <        assertEquals(2, s.availablePermits());
428 <        assertTrue(s.tryAcquire(2));
429 <        assertEquals(0, s.availablePermits());
430 <        assertFalse(s.tryAcquire());
425 >    public void testReducePermits()      { testReducePermits(false); }
426 >    public void testReducePermits_fair() { testReducePermits(true); }
427 >    public void testReducePermits(boolean fair) {
428 >        PublicSemaphore s = new PublicSemaphore(10, fair);
429 >        assertEquals(10, s.availablePermits());
430 >        s.reducePermits(0);
431 >        assertEquals(10, s.availablePermits());
432 >        s.reducePermits(1);
433 >        assertEquals(9, s.availablePermits());
434 >        s.reducePermits(10);
435 >        assertEquals(-1, s.availablePermits());
436 >        s.reducePermits(10);
437 >        assertEquals(-11, s.availablePermits());
438 >        s.reducePermits(0);
439 >        assertEquals(-11, s.availablePermits());
440      }
441  
442      /**
443 <     * Acquire and release of semaphore succeed if initially available
443 >     * a reserialized semaphore has same number of permits and
444 >     * fairness, but no queued threads
445       */
446 <    public void testAcquireReleaseInSameThread_fair() {
447 <        Semaphore s = new Semaphore(1, true);
446 >    public void testSerialization()      { testSerialization(false); }
447 >    public void testSerialization_fair() { testSerialization(true); }
448 >    public void testSerialization(boolean fair) {
449          try {
450 +            Semaphore s = new Semaphore(3, fair);
451              s.acquire();
495            s.release();
496            s.acquire();
497            s.release();
498            s.acquire();
499            s.release();
500            s.acquire();
501            s.release();
452              s.acquire();
453              s.release();
504            assertEquals(1, s.availablePermits());
505        } catch (InterruptedException e) {
506            unexpectedException();
507        }
508    }
454  
455 <    /**
456 <     * Acquire(n) and release(n) of semaphore succeed if initially available
457 <     */
458 <    public void testAcquireReleaseNInSameThread_fair() {
459 <        Semaphore s = new Semaphore(1, true);
460 <        try {
461 <            s.release(1);
462 <            s.acquire(1);
463 <            s.release(2);
464 <            s.acquire(2);
520 <            s.release(3);
521 <            s.acquire(3);
522 <            s.release(4);
523 <            s.acquire(4);
524 <            s.release(5);
525 <            s.acquire(5);
526 <            assertEquals(1, s.availablePermits());
527 <        } catch (InterruptedException e) {
528 <            unexpectedException();
529 <        }
530 <    }
455 >            Semaphore clone = serialClone(s);
456 >            assertEquals(fair, s.isFair());
457 >            assertEquals(fair, clone.isFair());
458 >            assertEquals(2, s.availablePermits());
459 >            assertEquals(2, clone.availablePermits());
460 >            clone.acquire();
461 >            clone.acquire();
462 >            clone.release();
463 >            assertEquals(2, s.availablePermits());
464 >            assertEquals(1, clone.availablePermits());
465  
466 <    /**
467 <     * Acquire(n) and release(n) of semaphore succeed if initially available
468 <     */
469 <    public void testAcquireUninterruptiblyReleaseNInSameThread_fair() {
470 <        Semaphore s = new Semaphore(1, true);
471 <        try {
472 <            s.release(1);
473 <            s.acquireUninterruptibly(1);
474 <            s.release(2);
475 <            s.acquireUninterruptibly(2);
476 <            s.release(3);
477 <            s.acquireUninterruptibly(3);
478 <            s.release(4);
479 <            s.acquireUninterruptibly(4);
480 <            s.release(5);
547 <            s.acquireUninterruptibly(5);
548 <            assertEquals(1, s.availablePermits());
549 <        } finally {
550 <        }
466 >            s = new Semaphore(0, fair);
467 >            Thread t = newStartedThread(new InterruptibleLockRunnable(s));
468 >            waitForQueuedThreads(s);
469 >            clone = serialClone(s);
470 >            assertEquals(fair, s.isFair());
471 >            assertEquals(fair, clone.isFair());
472 >            assertEquals(0, s.availablePermits());
473 >            assertEquals(0, clone.availablePermits());
474 >            assertTrue(s.hasQueuedThreads());
475 >            assertFalse(clone.hasQueuedThreads());
476 >            s.release();
477 >            awaitTermination(t);
478 >            assertFalse(s.hasQueuedThreads());
479 >            assertFalse(clone.hasQueuedThreads());
480 >        } catch (InterruptedException e) { threadUnexpectedException(e); }
481      }
482  
483      /**
484 <     * release(n) in one thread enables timed acquire(n) in another thread
484 >     * tryAcquire(n) succeeds when sufficient permits, else fails
485       */
486 <    public void testTimedAcquireReleaseNInSameThread_fair() {
487 <        Semaphore s = new Semaphore(1, true);
488 <        try {
489 <            s.release(1);
490 <            assertTrue(s.tryAcquire(1, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
491 <            s.release(2);
492 <            assertTrue(s.tryAcquire(2, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
493 <            s.release(3);
494 <            assertTrue(s.tryAcquire(3, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
495 <            s.release(4);
496 <            assertTrue(s.tryAcquire(4, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
497 <            s.release(5);
568 <            assertTrue(s.tryAcquire(5, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
569 <            assertEquals(1, s.availablePermits());
570 <        } catch (InterruptedException e) {
571 <            unexpectedException();
572 <        }
486 >    public void testTryAcquireNInSameThread()      { testTryAcquireNInSameThread(false); }
487 >    public void testTryAcquireNInSameThread_fair() { testTryAcquireNInSameThread(true); }
488 >    public void testTryAcquireNInSameThread(boolean fair) {
489 >        Semaphore s = new Semaphore(2, fair);
490 >        assertEquals(2, s.availablePermits());
491 >        assertFalse(s.tryAcquire(3));
492 >        assertEquals(2, s.availablePermits());
493 >        assertTrue(s.tryAcquire(2));
494 >        assertEquals(0, s.availablePermits());
495 >        assertFalse(s.tryAcquire(1));
496 >        assertFalse(s.tryAcquire(2));
497 >        assertEquals(0, s.availablePermits());
498      }
499  
500      /**
501 <     * release in one thread enables timed acquire in another thread
501 >     * acquire succeeds if permits available
502       */
503 <    public void testTimedAcquireReleaseInSameThread_fair() {
504 <        Semaphore s = new Semaphore(1, true);
505 <        try {
506 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
507 <            s.release();
508 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
509 <            s.release();
510 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
511 <            s.release();
512 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
513 <            s.release();
514 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
515 <            s.release();
503 >    public void testReleaseAcquireSameThread_acquire()       { testReleaseAcquireSameThread(false, AcquireMethod.acquire); }
504 >    public void testReleaseAcquireSameThread_acquire_fair()  { testReleaseAcquireSameThread(true, AcquireMethod.acquire); }
505 >    public void testReleaseAcquireSameThread_acquireN()      { testReleaseAcquireSameThread(false, AcquireMethod.acquireN); }
506 >    public void testReleaseAcquireSameThread_acquireN_fair() { testReleaseAcquireSameThread(true, AcquireMethod.acquireN); }
507 >    public void testReleaseAcquireSameThread_acquireUninterruptibly()       { testReleaseAcquireSameThread(false, AcquireMethod.acquireUninterruptibly); }
508 >    public void testReleaseAcquireSameThread_acquireUninterruptibly_fair()  { testReleaseAcquireSameThread(true, AcquireMethod.acquireUninterruptibly); }
509 >    public void testReleaseAcquireSameThread_acquireUninterruptiblyN()      { testReleaseAcquireSameThread(false, AcquireMethod.acquireUninterruptibly); }
510 >    public void testReleaseAcquireSameThread_acquireUninterruptiblyN_fair() { testReleaseAcquireSameThread(true, AcquireMethod.acquireUninterruptibly); }
511 >    public void testReleaseAcquireSameThread_tryAcquire()       { testReleaseAcquireSameThread(false, AcquireMethod.tryAcquire); }
512 >    public void testReleaseAcquireSameThread_tryAcquire_fair()  { testReleaseAcquireSameThread(true, AcquireMethod.tryAcquire); }
513 >    public void testReleaseAcquireSameThread_tryAcquireN()      { testReleaseAcquireSameThread(false, AcquireMethod.tryAcquireN); }
514 >    public void testReleaseAcquireSameThread_tryAcquireN_fair() { testReleaseAcquireSameThread(true, AcquireMethod.tryAcquireN); }
515 >    public void testReleaseAcquireSameThread_tryAcquireTimed()       { testReleaseAcquireSameThread(false, AcquireMethod.tryAcquireTimed); }
516 >    public void testReleaseAcquireSameThread_tryAcquireTimed_fair()  { testReleaseAcquireSameThread(true, AcquireMethod.tryAcquireTimed); }
517 >    public void testReleaseAcquireSameThread_tryAcquireTimedN()      { testReleaseAcquireSameThread(false, AcquireMethod.tryAcquireTimedN); }
518 >    public void testReleaseAcquireSameThread_tryAcquireTimedN_fair() { testReleaseAcquireSameThread(true, AcquireMethod.tryAcquireTimedN); }
519 >    public void testReleaseAcquireSameThread(boolean fair,
520 >                                             final AcquireMethod acquirer) {
521 >        Semaphore s = new Semaphore(1, fair);
522 >        for (int i = 1; i < 6; i++) {
523 >            s.release(i);
524 >            assertEquals(1 + i, s.availablePermits());
525 >            try {
526 >                acquirer.acquire(s, i);
527 >            } catch (InterruptedException e) { threadUnexpectedException(e); }
528              assertEquals(1, s.availablePermits());
592        } catch (InterruptedException e) {
593            unexpectedException();
529          }
530      }
531  
532      /**
533 <     * A release in one thread enables an acquire in another thread
533 >     * release in one thread enables acquire in another thread
534       */
535 <    public void testAcquireReleaseInDifferentThreads_fair() {
536 <        final Semaphore s = new Semaphore(0, true);
537 <        Thread t = new Thread(new Runnable() {
538 <                public void run() {
539 <                    try {
540 <                        s.acquire();
541 <                        s.acquire();
542 <                        s.acquire();
543 <                        s.acquire();
544 <                    } catch (InterruptedException ie) {
545 <                        threadUnexpectedException();
546 <                    }
547 <                }
548 <            });
549 <        try {
550 <            t.start();
551 <            Thread.sleep(SHORT_DELAY_MS);
552 <            s.release();
553 <            s.release();
554 <            s.release();
555 <            s.release();
556 <            s.release();
557 <            s.release();
558 <            t.join();
559 <            assertEquals(2, s.availablePermits());
560 <        } catch (InterruptedException e) {
561 <            unexpectedException();
562 <        }
563 <    }
564 <
565 <    /**
566 <     * release(n) in one thread enables acquire(n) in another thread
567 <     */
568 <    public void testAcquireReleaseNInDifferentThreads_fair() {
569 <        final Semaphore s = new Semaphore(0, true);
635 <        Thread t = new Thread(new Runnable() {
636 <                public void run() {
637 <                    try {
638 <                        s.acquire();
639 <                        s.release(2);
640 <                        s.acquire();
641 <                    } catch (InterruptedException ie) {
642 <                        threadUnexpectedException();
643 <                    }
644 <                }
645 <            });
646 <        try {
647 <            t.start();
648 <            Thread.sleep(SHORT_DELAY_MS);
649 <            s.release(2);
650 <            s.acquire(2);
651 <            s.release(1);
652 <            t.join();
653 <        } catch (InterruptedException e) {
654 <            unexpectedException();
655 <        }
656 <    }
657 <
658 <    /**
659 <     * release(n) in one thread enables acquire(n) in another thread
660 <     */
661 <    public void testAcquireReleaseNInDifferentThreads_fair2() {
662 <        final Semaphore s = new Semaphore(0, true);
663 <        Thread t = new Thread(new Runnable() {
664 <                public void run() {
665 <                    try {
666 <                        s.acquire(2);
667 <                        s.acquire(2);
668 <                        s.release(4);
669 <                    } catch (InterruptedException ie) {
670 <                        threadUnexpectedException();
671 <                    }
672 <                }
673 <            });
674 <        try {
675 <            t.start();
676 <            Thread.sleep(SHORT_DELAY_MS);
677 <            s.release(6);
678 <            s.acquire(2);
679 <            s.acquire(2);
680 <            s.release(2);
681 <            t.join();
682 <        } catch (InterruptedException e) {
683 <            unexpectedException();
684 <        }
685 <    }
686 <
687 <
688 <
689 <
690 <
691 <    /**
692 <     * release in one thread enables timed acquire in another thread
693 <     */
694 <    public void testTimedAcquireReleaseInDifferentThreads_fair() {
695 <        final Semaphore s = new Semaphore(1, true);
696 <        Thread t = new Thread(new Runnable() {
697 <                public void run() {
698 <                    try {
699 <                        threadAssertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
700 <                        threadAssertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
701 <                        threadAssertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
702 <                        threadAssertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
703 <                        threadAssertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
704 <
705 <                    } catch (InterruptedException ie) {
706 <                        threadUnexpectedException();
707 <                    }
708 <                }
709 <            });
710 <        t.start();
711 <        try {
712 <            s.release();
713 <            s.release();
714 <            s.release();
715 <            s.release();
716 <            s.release();
717 <            t.join();
718 <        } catch (InterruptedException e) {
719 <            unexpectedException();
720 <        }
721 <    }
722 <
723 <    /**
724 <     * release(n) in one thread enables timed acquire(n) in another thread
725 <     */
726 <    public void testTimedAcquireReleaseNInDifferentThreads_fair() {
727 <        final Semaphore s = new Semaphore(2, true);
728 <        Thread t = new Thread(new Runnable() {
729 <                public void run() {
730 <                    try {
731 <                        threadAssertTrue(s.tryAcquire(2, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
732 <                        s.release(2);
733 <                        threadAssertTrue(s.tryAcquire(2, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
734 <                        s.release(2);
735 <                    } catch (InterruptedException ie) {
736 <                        threadUnexpectedException();
737 <                    }
738 <                }
739 <            });
740 <        t.start();
741 <        try {
742 <            assertTrue(s.tryAcquire(2, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
743 <            s.release(2);
744 <            assertTrue(s.tryAcquire(2, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
745 <            s.release(2);
746 <            t.join();
747 <        } catch (InterruptedException e) {
748 <            unexpectedException();
749 <        }
750 <    }
751 <
752 <    /**
753 <     * A waiting acquire blocks interruptibly
754 <     */
755 <    public void testAcquire_InterruptedException_fair() {
756 <        final Semaphore s = new Semaphore(0, true);
757 <        Thread t = new Thread(new Runnable() {
758 <                public void run() {
759 <                    try {
760 <                        s.acquire();
761 <                        threadShouldThrow();
762 <                    } catch (InterruptedException success) {}
763 <                }
764 <            });
765 <        t.start();
766 <        try {
767 <            Thread.sleep(SHORT_DELAY_MS);
768 <            t.interrupt();
769 <            t.join();
770 <        } catch (InterruptedException e) {
771 <            unexpectedException();
772 <        }
773 <    }
774 <
775 <    /**
776 <     * A waiting acquire(n) blocks interruptibly
777 <     */
778 <    public void testAcquireN_InterruptedException_fair() {
779 <        final Semaphore s = new Semaphore(2, true);
780 <        Thread t = new Thread(new Runnable() {
781 <                public void run() {
782 <                    try {
783 <                        s.acquire(3);
784 <                        threadShouldThrow();
785 <                    } catch (InterruptedException success) {}
786 <                }
787 <            });
788 <        t.start();
789 <        try {
790 <            Thread.sleep(SHORT_DELAY_MS);
791 <            t.interrupt();
792 <            t.join();
793 <        } catch (InterruptedException e) {
794 <            unexpectedException();
795 <        }
796 <    }
797 <
798 <    /**
799 <     *  A waiting tryAcquire blocks interruptibly
800 <     */
801 <    public void testTryAcquire_InterruptedException_fair() {
802 <        final Semaphore s = new Semaphore(0, true);
803 <        Thread t = new Thread(new Runnable() {
804 <                public void run() {
805 <                    try {
806 <                        s.tryAcquire(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
807 <                        threadShouldThrow();
808 <                    } catch (InterruptedException success) {
809 <                    }
810 <                }
811 <            });
812 <        t.start();
813 <        try {
814 <            Thread.sleep(SHORT_DELAY_MS);
815 <            t.interrupt();
816 <            t.join();
817 <        } catch (InterruptedException e) {
818 <            unexpectedException();
819 <        }
820 <    }
821 <
822 <    /**
823 <     *  A waiting tryAcquire(n) blocks interruptibly
824 <     */
825 <    public void testTryAcquireN_InterruptedException_fair() {
826 <        final Semaphore s = new Semaphore(1, true);
827 <        Thread t = new Thread(new Runnable() {
828 <                public void run() {
829 <                    try {
830 <                        s.tryAcquire(4, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
831 <                        threadShouldThrow();
832 <                    } catch (InterruptedException success) {
833 <                    }
834 <                }
835 <            });
836 <        t.start();
837 <        try {
838 <            Thread.sleep(SHORT_DELAY_MS);
839 <            t.interrupt();
840 <            t.join();
841 <        } catch (InterruptedException e) {
842 <            unexpectedException();
843 <        }
844 <    }
845 <
846 <    /**
847 <     * getQueueLength reports number of waiting threads
848 <     */
849 <    public void testGetQueueLength_fair() {
850 <        final Semaphore lock = new Semaphore(1, true);
851 <        Thread t1 = new Thread(new InterruptedLockRunnable(lock));
852 <        Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
853 <        try {
854 <            assertEquals(0, lock.getQueueLength());
855 <            lock.acquireUninterruptibly();
856 <            t1.start();
857 <            Thread.sleep(SHORT_DELAY_MS);
858 <            assertEquals(1, lock.getQueueLength());
859 <            t2.start();
860 <            Thread.sleep(SHORT_DELAY_MS);
861 <            assertEquals(2, lock.getQueueLength());
862 <            t1.interrupt();
863 <            Thread.sleep(SHORT_DELAY_MS);
864 <            assertEquals(1, lock.getQueueLength());
865 <            lock.release();
866 <            Thread.sleep(SHORT_DELAY_MS);
867 <            assertEquals(0, lock.getQueueLength());
868 <            t1.join();
869 <            t2.join();
870 <        } catch (Exception e) {
871 <            unexpectedException();
535 >    public void testReleaseAcquireDifferentThreads_acquire()       { testReleaseAcquireDifferentThreads(false, AcquireMethod.acquire); }
536 >    public void testReleaseAcquireDifferentThreads_acquire_fair()  { testReleaseAcquireDifferentThreads(true, AcquireMethod.acquire); }
537 >    public void testReleaseAcquireDifferentThreads_acquireN()      { testReleaseAcquireDifferentThreads(false, AcquireMethod.acquireN); }
538 >    public void testReleaseAcquireDifferentThreads_acquireN_fair() { testReleaseAcquireDifferentThreads(true, AcquireMethod.acquireN); }
539 >    public void testReleaseAcquireDifferentThreads_acquireUninterruptibly()       { testReleaseAcquireDifferentThreads(false, AcquireMethod.acquireUninterruptibly); }
540 >    public void testReleaseAcquireDifferentThreads_acquireUninterruptibly_fair()  { testReleaseAcquireDifferentThreads(true, AcquireMethod.acquireUninterruptibly); }
541 >    public void testReleaseAcquireDifferentThreads_acquireUninterruptiblyN()      { testReleaseAcquireDifferentThreads(false, AcquireMethod.acquireUninterruptibly); }
542 >    public void testReleaseAcquireDifferentThreads_acquireUninterruptiblyN_fair() { testReleaseAcquireDifferentThreads(true, AcquireMethod.acquireUninterruptibly); }
543 >    public void testReleaseAcquireDifferentThreads_tryAcquireTimed()       { testReleaseAcquireDifferentThreads(false, AcquireMethod.tryAcquireTimed); }
544 >    public void testReleaseAcquireDifferentThreads_tryAcquireTimed_fair()  { testReleaseAcquireDifferentThreads(true, AcquireMethod.tryAcquireTimed); }
545 >    public void testReleaseAcquireDifferentThreads_tryAcquireTimedN()      { testReleaseAcquireDifferentThreads(false, AcquireMethod.tryAcquireTimedN); }
546 >    public void testReleaseAcquireDifferentThreads_tryAcquireTimedN_fair() { testReleaseAcquireDifferentThreads(true, AcquireMethod.tryAcquireTimedN); }
547 >    public void testReleaseAcquireDifferentThreads(boolean fair,
548 >                                                   final AcquireMethod acquirer) {
549 >        final Semaphore s = new Semaphore(0, fair);
550 >        final int rounds = 4;
551 >        long startTime = System.nanoTime();
552 >        Thread t = newStartedThread(new CheckedRunnable() {
553 >            public void realRun() throws InterruptedException {
554 >                for (int i = 0; i < rounds; i++) {
555 >                    assertFalse(s.hasQueuedThreads());
556 >                    if (i % 2 == 0)
557 >                        acquirer.acquire(s);
558 >                    else
559 >                        acquirer.acquire(s, 3);
560 >                }}});
561 >
562 >        for (int i = 0; i < rounds; i++) {
563 >            while (! (s.availablePermits() == 0 && s.hasQueuedThreads()))
564 >                Thread.yield();
565 >            assertTrue(t.isAlive());
566 >            if (i % 2 == 0)
567 >                s.release();
568 >            else
569 >                s.release(3);
570          }
571 +        awaitTermination(t);
572 +        assertEquals(0, s.availablePermits());
573 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
574      }
575  
875
576      /**
577 <     * a deserialized serialized semaphore has same number of permits
577 >     * fair locks are strictly FIFO
578       */
579 <    public void testSerialization_fair() {
580 <        Semaphore l = new Semaphore(3, true);
581 <
582 <        try {
583 <            l.acquire();
584 <            l.release();
585 <            ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
586 <            ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
587 <            out.writeObject(l);
588 <            out.close();
589 <
590 <            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
591 <            ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
592 <            Semaphore r = (Semaphore) in.readObject();
593 <            assertEquals(3, r.availablePermits());
594 <            assertTrue(r.isFair());
595 <            r.acquire();
596 <            r.release();
597 <        } catch (Exception e) {
598 <            unexpectedException();
599 <        }
600 <    }
579 >    public void testFairLocksFifo() {
580 >        final PublicSemaphore s = new PublicSemaphore(1, true);
581 >        final CountDownLatch pleaseRelease = new CountDownLatch(1);
582 >        Thread t1 = newStartedThread(new CheckedRunnable() {
583 >            public void realRun() throws InterruptedException {
584 >                // Will block; permits are available, but not three
585 >                s.acquire(3);
586 >            }});
587 >
588 >        waitForQueuedThreads(s);
589 >
590 >        Thread t2 = newStartedThread(new CheckedRunnable() {
591 >            public void realRun() throws InterruptedException {
592 >                // Will fail, even though 1 permit is available
593 >                assertFalse(s.tryAcquire(0L, MILLISECONDS));
594 >                assertFalse(s.tryAcquire(1, 0L, MILLISECONDS));
595 >
596 >                // untimed tryAcquire will barge and succeed
597 >                assertTrue(s.tryAcquire());
598 >                s.release(2);
599 >                assertTrue(s.tryAcquire(2));
600 >                s.release();
601 >
602 >                pleaseRelease.countDown();
603 >                // Will queue up behind t1, even though 1 permit is available
604 >                s.acquire();
605 >            }});
606 >
607 >        await(pleaseRelease);
608 >        waitForQueuedThread(s, t2);
609 >        s.release(2);
610 >        awaitTermination(t1);
611 >        assertTrue(t2.isAlive());
612 >        s.release();
613 >        awaitTermination(t2);
614 >   }
615  
616      /**
617       * toString indicates current number of permits
618       */
619 <    public void testToString() {
620 <        Semaphore s = new Semaphore(0);
621 <        String us = s.toString();
622 <        assertTrue(us.indexOf("Permits = 0") >= 0);
623 <        s.release();
910 <        String s1 = s.toString();
911 <        assertTrue(s1.indexOf("Permits = 1") >= 0);
619 >    public void testToString()      { testToString(false); }
620 >    public void testToString_fair() { testToString(true); }
621 >    public void testToString(boolean fair) {
622 >        PublicSemaphore s = new PublicSemaphore(0, fair);
623 >        assertTrue(s.toString().contains("Permits = 0"));
624          s.release();
625 <        String s2 = s.toString();
626 <        assertTrue(s2.indexOf("Permits = 2") >= 0);
625 >        assertTrue(s.toString().contains("Permits = 1"));
626 >        s.release(2);
627 >        assertTrue(s.toString().contains("Permits = 3"));
628 >        s.reducePermits(5);
629 >        assertTrue(s.toString().contains("Permits = -2"));
630      }
631  
632   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines