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.14 by dl, Sat Jan 10 01:41:59 2004 UTC vs.
Revision 1.45 by jsr166, Tue Aug 13 00:46:27 2019 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
5 < * Other contributors include Andrew Wright, Jeffrey Hayes,
6 < * Pat Fisher, Mike Judd.
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.*;
9 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 >
11 > import java.util.Collection;
12 > import java.util.concurrent.CountDownLatch;
13 > import java.util.concurrent.Semaphore;
14 >
15 > import junit.framework.Test;
16 > import junit.framework.TestSuite;
17  
18   public class SemaphoreTest extends JSR166TestCase {
19      public static void main(String[] args) {
20 <        junit.textui.TestRunner.run (suite());  
20 >        main(suite(), args);
21      }
22      public static Test suite() {
23 <        return new TestSuite(SemaphoreTest.class);
23 >        return new TestSuite(SemaphoreTest.class);
24      }
25  
26      /**
27       * Subclass to expose protected methods
28       */
29      static class PublicSemaphore extends Semaphore {
30 <        PublicSemaphore(int p, boolean f) { super(p, f); }
31 <        public Collection<Thread> getQueuedThreads() {
32 <            return super.getQueuedThreads();
30 >        PublicSemaphore(int permits) { super(permits); }
31 >        PublicSemaphore(int permits, boolean fair) { super(permits, fair); }
32 >        public Collection<Thread> getQueuedThreads() {
33 >            return super.getQueuedThreads();
34          }
35 <        public void reducePermits(int p) {
36 <            super.reducePermits(p);
35 >        public boolean hasQueuedThread(Thread t) {
36 >            return super.getQueuedThreads().contains(t);
37 >        }
38 >        public void reducePermits(int reduction) {
39 >            super.reducePermits(reduction);
40          }
41      }
42  
43      /**
44       * A runnable calling acquire
45       */
46 <    class InterruptibleLockRunnable implements Runnable {
46 >    class InterruptibleLockRunnable extends CheckedRunnable {
47          final Semaphore lock;
48 <        InterruptibleLockRunnable(Semaphore l) { lock = l; }
49 <        public void run() {
48 >        InterruptibleLockRunnable(Semaphore s) { lock = s; }
49 >        public void realRun() {
50              try {
51                  lock.acquire();
52 <            } catch(InterruptedException success){}
52 >            }
53 >            catch (InterruptedException ignored) {}
54          }
55      }
56  
48
57      /**
58 <     * A runnable calling acquire that expects to be
51 <     * interrupted
58 >     * A runnable calling acquire that expects to be interrupted
59       */
60 <    class InterruptedLockRunnable implements Runnable {
60 >    class InterruptedLockRunnable extends CheckedInterruptedRunnable {
61          final Semaphore lock;
62 <        InterruptedLockRunnable(Semaphore l) { lock = l; }
63 <        public void run() {
64 <            try {
65 <                lock.acquire();
66 <                threadShouldThrow();
67 <            } catch(InterruptedException success){}
62 >        InterruptedLockRunnable(Semaphore s) { lock = s; }
63 >        public void realRun() throws InterruptedException {
64 >            lock.acquire();
65 >        }
66 >    }
67 >
68 >    /**
69 >     * Spin-waits until s.hasQueuedThread(t) becomes true.
70 >     */
71 >    void waitForQueuedThread(PublicSemaphore s, Thread t) {
72 >        long startTime = System.nanoTime();
73 >        while (!s.hasQueuedThread(t)) {
74 >            if (millisElapsedSince(startTime) > LONG_DELAY_MS)
75 >                throw new AssertionError("timed out");
76 >            Thread.yield();
77 >        }
78 >        assertTrue(s.hasQueuedThreads());
79 >        assertTrue(t.isAlive());
80 >    }
81 >
82 >    /**
83 >     * Spin-waits until s.hasQueuedThreads() becomes true.
84 >     */
85 >    void waitForQueuedThreads(Semaphore s) {
86 >        long startTime = System.nanoTime();
87 >        while (!s.hasQueuedThreads()) {
88 >            if (millisElapsedSince(startTime) > LONG_DELAY_MS)
89 >                throw new AssertionError("timed out");
90 >            Thread.yield();
91 >        }
92 >    }
93 >
94 >    enum AcquireMethod {
95 >        acquire() {
96 >            void acquire(Semaphore s) throws InterruptedException {
97 >                s.acquire();
98 >            }
99 >        },
100 >        acquireN() {
101 >            void acquire(Semaphore s, int permits) throws InterruptedException {
102 >                s.acquire(permits);
103 >            }
104 >        },
105 >        acquireUninterruptibly() {
106 >            void acquire(Semaphore s) {
107 >                s.acquireUninterruptibly();
108 >            }
109 >        },
110 >        acquireUninterruptiblyN() {
111 >            void acquire(Semaphore s, int permits) {
112 >                s.acquireUninterruptibly(permits);
113 >            }
114 >        },
115 >        tryAcquire() {
116 >            void acquire(Semaphore s) {
117 >                assertTrue(s.tryAcquire());
118 >            }
119 >        },
120 >        tryAcquireN() {
121 >            void acquire(Semaphore s, int permits) {
122 >                assertTrue(s.tryAcquire(permits));
123 >            }
124 >        },
125 >        tryAcquireTimed() {
126 >            void acquire(Semaphore s) throws InterruptedException {
127 >                assertTrue(s.tryAcquire(2 * LONG_DELAY_MS, MILLISECONDS));
128 >            }
129 >            Thread.State parkedState() { return Thread.State.TIMED_WAITING; }
130 >        },
131 >        tryAcquireTimedN {
132 >            void acquire(Semaphore s, int permits) throws InterruptedException {
133 >                assertTrue(s.tryAcquire(permits, 2 * LONG_DELAY_MS, MILLISECONDS));
134 >            }
135 >            Thread.State parkedState() { return Thread.State.TIMED_WAITING; }
136 >        };
137 >
138 >        // Intentionally meta-circular
139 >
140 >        /** Acquires 1 permit. */
141 >        void acquire(Semaphore s) throws InterruptedException {
142 >            acquire(s, 1);
143 >        }
144 >        /** Acquires the given number of permits. */
145 >        void acquire(Semaphore s, int permits) throws InterruptedException {
146 >            for (int i = 0; i < permits; i++)
147 >                acquire(s);
148          }
149 +        Thread.State parkedState() { return Thread.State.WAITING; }
150      }
151  
152      /**
153       * Zero, negative, and positive initial values are allowed in constructor
154       */
155 <    public void testConstructor() {
156 <        Semaphore s0 = new Semaphore(0, false);
157 <        assertEquals(0, s0.availablePermits());
158 <        assertFalse(s0.isFair());
159 <        Semaphore s1 = new Semaphore(-1, false);
160 <        assertEquals(-1, s1.availablePermits());
161 <        assertFalse(s1.isFair());
162 <        Semaphore s2 = new Semaphore(-1, false);
75 <        assertEquals(-1, s2.availablePermits());
76 <        assertFalse(s2.isFair());
155 >    public void testConstructor()      { testConstructor(false); }
156 >    public void testConstructor_fair() { testConstructor(true); }
157 >    public void testConstructor(boolean fair) {
158 >        for (int permits : new int[] { -42, -1, 0, 1, 42 }) {
159 >            Semaphore s = new Semaphore(permits, fair);
160 >            assertEquals(permits, s.availablePermits());
161 >            assertEquals(fair, s.isFair());
162 >        }
163      }
164  
165      /**
166       * Constructor without fairness argument behaves as nonfair
167       */
168 <    public void testConstructor2() {
169 <        Semaphore s0 = new Semaphore(0);
170 <        assertEquals(0, s0.availablePermits());
171 <        assertFalse(s0.isFair());
172 <        Semaphore s1 = new Semaphore(-1);
173 <        assertEquals(-1, s1.availablePermits());
88 <        assertFalse(s1.isFair());
89 <        Semaphore s2 = new Semaphore(-1);
90 <        assertEquals(-1, s2.availablePermits());
91 <        assertFalse(s2.isFair());
168 >    public void testConstructorDefaultsToNonFair() {
169 >        for (int permits : new int[] { -42, -1, 0, 1, 42 }) {
170 >            Semaphore s = new Semaphore(permits);
171 >            assertEquals(permits, s.availablePermits());
172 >            assertFalse(s.isFair());
173 >        }
174      }
175  
176      /**
177       * tryAcquire succeeds when sufficient permits, else fails
178       */
179 <    public void testTryAcquireInSameThread() {
180 <        Semaphore s = new Semaphore(2, false);
179 >    public void testTryAcquireInSameThread()      { testTryAcquireInSameThread(false); }
180 >    public void testTryAcquireInSameThread_fair() { testTryAcquireInSameThread(true); }
181 >    public void testTryAcquireInSameThread(boolean fair) {
182 >        Semaphore s = new Semaphore(2, fair);
183          assertEquals(2, s.availablePermits());
184          assertTrue(s.tryAcquire());
185          assertTrue(s.tryAcquire());
186          assertEquals(0, s.availablePermits());
187          assertFalse(s.tryAcquire());
188 +        assertFalse(s.tryAcquire());
189 +        assertEquals(0, s.availablePermits());
190      }
191  
192      /**
193 <     * Acquire and release of semaphore succeed if initially available
193 >     * timed tryAcquire times out
194       */
195 <    public void testAcquireReleaseInSameThread() {
196 <        Semaphore s = new Semaphore(1, false);
197 <        try {
198 <            s.acquire();
199 <            s.release();
200 <            s.acquire();
201 <            s.release();
202 <            s.acquire();
203 <            s.release();
204 <            s.acquire();
205 <            s.release();
206 <            s.acquire();
207 <            s.release();
208 <            assertEquals(1, s.availablePermits());
209 <        } catch( InterruptedException e){
210 <            unexpectedException();
195 >    public void testTryAcquire_timeout() throws InterruptedException {
196 >        final boolean fair = randomBoolean();
197 >        final Semaphore s = new Semaphore(0, fair);
198 >        final long startTime = System.nanoTime();
199 >        assertFalse(s.tryAcquire(timeoutMillis(), MILLISECONDS));
200 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
201 >    }
202 >
203 >    /**
204 >     * timed tryAcquire(N) times out
205 >     */
206 >    public void testTryAcquireN_timeout() throws InterruptedException {
207 >        final boolean fair = randomBoolean();
208 >        final Semaphore s = new Semaphore(2, fair);
209 >        final long startTime = System.nanoTime();
210 >        assertFalse(s.tryAcquire(3, timeoutMillis(), MILLISECONDS));
211 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
212 >    }
213 >
214 >    /**
215 >     * acquire(), acquire(N), timed tryAcquired, timed tryAcquire(N)
216 >     * are interruptible
217 >     */
218 >    public void testInterruptible_acquire()               { testInterruptible(false, AcquireMethod.acquire); }
219 >    public void testInterruptible_acquire_fair()          { testInterruptible(true,  AcquireMethod.acquire); }
220 >    public void testInterruptible_acquireN()              { testInterruptible(false, AcquireMethod.acquireN); }
221 >    public void testInterruptible_acquireN_fair()         { testInterruptible(true,  AcquireMethod.acquireN); }
222 >    public void testInterruptible_tryAcquireTimed()       { testInterruptible(false, AcquireMethod.tryAcquireTimed); }
223 >    public void testInterruptible_tryAcquireTimed_fair()  { testInterruptible(true,  AcquireMethod.tryAcquireTimed); }
224 >    public void testInterruptible_tryAcquireTimedN()      { testInterruptible(false, AcquireMethod.tryAcquireTimedN); }
225 >    public void testInterruptible_tryAcquireTimedN_fair() { testInterruptible(true,  AcquireMethod.tryAcquireTimedN); }
226 >    public void testInterruptible(boolean fair, final AcquireMethod acquirer) {
227 >        final PublicSemaphore s = new PublicSemaphore(0, fair);
228 >        final java.util.concurrent.CyclicBarrier pleaseInterrupt
229 >            = new java.util.concurrent.CyclicBarrier(2);
230 >        Thread t = newStartedThread(new CheckedRunnable() {
231 >            public void realRun() {
232 >                // Interrupt before acquire
233 >                Thread.currentThread().interrupt();
234 >                try {
235 >                    acquirer.acquire(s);
236 >                    shouldThrow();
237 >                } catch (InterruptedException success) {}
238 >                assertFalse(Thread.interrupted());
239 >
240 >                // Interrupt before acquire(N)
241 >                Thread.currentThread().interrupt();
242 >                try {
243 >                    acquirer.acquire(s, 3);
244 >                    shouldThrow();
245 >                } catch (InterruptedException success) {}
246 >                assertFalse(Thread.interrupted());
247 >
248 >                // Interrupt during acquire
249 >                await(pleaseInterrupt);
250 >                try {
251 >                    acquirer.acquire(s);
252 >                    shouldThrow();
253 >                } catch (InterruptedException success) {}
254 >                assertFalse(Thread.interrupted());
255 >
256 >                // Interrupt during acquire(N)
257 >                await(pleaseInterrupt);
258 >                try {
259 >                    acquirer.acquire(s, 3);
260 >                    shouldThrow();
261 >                } catch (InterruptedException success) {}
262 >                assertFalse(Thread.interrupted());
263 >            }});
264 >
265 >        for (int n = 2; n-->0; ) {
266 >            await(pleaseInterrupt);
267 >            assertThreadBlocks(t, acquirer.parkedState());
268 >            t.interrupt();
269          }
126    }
270  
271 <    /**
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 <        }
271 >        awaitTermination(t);
272      }
273  
274      /**
275 <     * Timed Acquire and release of semaphore succeed if
276 <     * initially available
275 >     * acquireUninterruptibly(), acquireUninterruptibly(N) are
276 >     * uninterruptible
277       */
278 <    public void testTimedAcquireReleaseInSameThread() {
279 <        Semaphore s = new Semaphore(1, false);
280 <        try {
281 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
282 <            s.release();
283 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
284 <            s.release();
285 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
286 <            s.release();
287 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
288 <            s.release();
289 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
290 <            s.release();
291 <            assertEquals(1, s.availablePermits());
292 <        } catch( InterruptedException e){
293 <            unexpectedException();
294 <        }
295 <    }
278 >    public void testUninterruptible_acquireUninterruptibly()       { testUninterruptible(false, AcquireMethod.acquireUninterruptibly); }
279 >    public void testUninterruptible_acquireUninterruptibly_fair()  { testUninterruptible(true,  AcquireMethod.acquireUninterruptibly); }
280 >    public void testUninterruptible_acquireUninterruptiblyN()      { testUninterruptible(false, AcquireMethod.acquireUninterruptiblyN); }
281 >    public void testUninterruptible_acquireUninterruptiblyN_fair() { testUninterruptible(true,  AcquireMethod.acquireUninterruptiblyN); }
282 >    public void testUninterruptible(boolean fair, final AcquireMethod acquirer) {
283 >        final PublicSemaphore s = new PublicSemaphore(0, fair);
284 >        final Semaphore pleaseInterrupt = new Semaphore(-1, fair);
285 >
286 >        Thread t1 = newStartedThread(new CheckedRunnable() {
287 >            public void realRun() throws InterruptedException {
288 >                // Interrupt before acquire
289 >                pleaseInterrupt.release();
290 >                Thread.currentThread().interrupt();
291 >                acquirer.acquire(s);
292 >                assertTrue(Thread.interrupted());
293 >            }});
294 >
295 >        Thread t2 = newStartedThread(new CheckedRunnable() {
296 >            public void realRun() throws InterruptedException {
297 >                // Interrupt during acquire
298 >                pleaseInterrupt.release();
299 >                acquirer.acquire(s);
300 >                assertTrue(Thread.interrupted());
301 >            }});
302 >
303 >        await(pleaseInterrupt);
304 >        waitForQueuedThread(s, t1);
305 >        waitForQueuedThread(s, t2);
306 >        t2.interrupt();
307  
308 <    /**
309 <     * 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
206 <     */
207 <    public void testUninterruptibleAcquireReleaseInDifferentThreads() {
208 <        final Semaphore s = new Semaphore(0, false);
209 <        Thread t = new Thread(new Runnable() {
210 <                public void run() {
211 <                    s.acquireUninterruptibly();
212 <                    s.release();
213 <                    s.release();
214 <                    s.acquireUninterruptibly();
215 <                }
216 <            });
217 <        try {
218 <            t.start();
219 <            Thread.sleep(SHORT_DELAY_MS);
220 <            s.release();
221 <            s.release();
222 <            s.acquireUninterruptibly();
223 <            s.acquireUninterruptibly();
224 <            s.release();
225 <            t.join();
226 <        } catch( InterruptedException e){
227 <            unexpectedException();
228 <        }
229 <    }
308 >        assertThreadBlocks(t1, Thread.State.WAITING);
309 >        assertThreadBlocks(t2, Thread.State.WAITING);
310  
311 +        s.release(2);
312  
313 <    /**
314 <     *  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 <            });
250 <        try {
251 <            t.start();
252 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
253 <            s.release();
254 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
255 <            s.release();
256 <            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 <    }
285 <    
286 <    /**
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 <        }
313 >        awaitTermination(t1);
314 >        awaitTermination(t2);
315      }
316  
317      /**
318       * hasQueuedThreads reports whether there are waiting threads
319       */
320 <    public void testHasQueuedThreads() {
321 <        final Semaphore lock = new Semaphore(1, false);
322 <        Thread t1 = new Thread(new InterruptedLockRunnable(lock));
323 <        Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
324 <        try {
325 <            assertFalse(lock.hasQueuedThreads());
326 <            lock.acquireUninterruptibly();
327 <            t1.start();
328 <            Thread.sleep(SHORT_DELAY_MS);
329 <            assertTrue(lock.hasQueuedThreads());
330 <            t2.start();
331 <            Thread.sleep(SHORT_DELAY_MS);
332 <            assertTrue(lock.hasQueuedThreads());
333 <            t1.interrupt();
334 <            Thread.sleep(SHORT_DELAY_MS);
335 <            assertTrue(lock.hasQueuedThreads());
336 <            lock.release();
337 <            Thread.sleep(SHORT_DELAY_MS);
338 <            assertFalse(lock.hasQueuedThreads());
332 <            t1.join();
333 <            t2.join();
334 <        } catch(Exception e){
335 <            unexpectedException();
336 <        }
337 <    }
320 >    public void testHasQueuedThreads()      { testHasQueuedThreads(false); }
321 >    public void testHasQueuedThreads_fair() { testHasQueuedThreads(true); }
322 >    public void testHasQueuedThreads(boolean fair) {
323 >        final PublicSemaphore lock = new PublicSemaphore(1, fair);
324 >        assertFalse(lock.hasQueuedThreads());
325 >        lock.acquireUninterruptibly();
326 >        Thread t1 = newStartedThread(new InterruptedLockRunnable(lock));
327 >        waitForQueuedThread(lock, t1);
328 >        assertTrue(lock.hasQueuedThreads());
329 >        Thread t2 = newStartedThread(new InterruptibleLockRunnable(lock));
330 >        waitForQueuedThread(lock, t2);
331 >        assertTrue(lock.hasQueuedThreads());
332 >        t1.interrupt();
333 >        awaitTermination(t1);
334 >        assertTrue(lock.hasQueuedThreads());
335 >        lock.release();
336 >        awaitTermination(t2);
337 >        assertFalse(lock.hasQueuedThreads());
338 >    }
339  
340      /**
341       * getQueueLength reports number of waiting threads
342       */
343 <    public void testGetQueueLength() {
344 <        final Semaphore lock = new Semaphore(1, false);
345 <        Thread t1 = new Thread(new InterruptedLockRunnable(lock));
346 <        Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
347 <        try {
348 <            assertEquals(0, lock.getQueueLength());
349 <            lock.acquireUninterruptibly();
350 <            t1.start();
351 <            Thread.sleep(SHORT_DELAY_MS);
352 <            assertEquals(1, lock.getQueueLength());
353 <            t2.start();
354 <            Thread.sleep(SHORT_DELAY_MS);
355 <            assertEquals(2, lock.getQueueLength());
356 <            t1.interrupt();
357 <            Thread.sleep(SHORT_DELAY_MS);
358 <            assertEquals(1, lock.getQueueLength());
359 <            lock.release();
360 <            Thread.sleep(SHORT_DELAY_MS);
361 <            assertEquals(0, lock.getQueueLength());
361 <            t1.join();
362 <            t2.join();
363 <        } catch(Exception e){
364 <            unexpectedException();
365 <        }
366 <    }
343 >    public void testGetQueueLength()      { testGetQueueLength(false); }
344 >    public void testGetQueueLength_fair() { testGetQueueLength(true); }
345 >    public void testGetQueueLength(boolean fair) {
346 >        final PublicSemaphore lock = new PublicSemaphore(1, fair);
347 >        assertEquals(0, lock.getQueueLength());
348 >        lock.acquireUninterruptibly();
349 >        Thread t1 = newStartedThread(new InterruptedLockRunnable(lock));
350 >        waitForQueuedThread(lock, t1);
351 >        assertEquals(1, lock.getQueueLength());
352 >        Thread t2 = newStartedThread(new InterruptibleLockRunnable(lock));
353 >        waitForQueuedThread(lock, t2);
354 >        assertEquals(2, lock.getQueueLength());
355 >        t1.interrupt();
356 >        awaitTermination(t1);
357 >        assertEquals(1, lock.getQueueLength());
358 >        lock.release();
359 >        awaitTermination(t2);
360 >        assertEquals(0, lock.getQueueLength());
361 >    }
362  
363      /**
364       * getQueuedThreads includes waiting threads
365       */
366 <    public void testGetQueuedThreads() {
367 <        final PublicSemaphore lock = new PublicSemaphore(1, false);
368 <        Thread t1 = new Thread(new InterruptedLockRunnable(lock));
369 <        Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
370 <        try {
371 <            assertTrue(lock.getQueuedThreads().isEmpty());
372 <            lock.acquireUninterruptibly();
373 <            assertTrue(lock.getQueuedThreads().isEmpty());
374 <            t1.start();
375 <            Thread.sleep(SHORT_DELAY_MS);
376 <            assertTrue(lock.getQueuedThreads().contains(t1));
377 <            t2.start();
378 <            Thread.sleep(SHORT_DELAY_MS);
379 <            assertTrue(lock.getQueuedThreads().contains(t1));
380 <            assertTrue(lock.getQueuedThreads().contains(t2));
381 <            t1.interrupt();
382 <            Thread.sleep(SHORT_DELAY_MS);
383 <            assertFalse(lock.getQueuedThreads().contains(t1));
384 <            assertTrue(lock.getQueuedThreads().contains(t2));
385 <            lock.release();
386 <            Thread.sleep(SHORT_DELAY_MS);
387 <            assertTrue(lock.getQueuedThreads().isEmpty());
393 <            t1.join();
394 <            t2.join();
395 <        } catch(Exception e){
396 <            unexpectedException();
397 <        }
398 <    }
366 >    public void testGetQueuedThreads()      { testGetQueuedThreads(false); }
367 >    public void testGetQueuedThreads_fair() { testGetQueuedThreads(true); }
368 >    public void testGetQueuedThreads(boolean fair) {
369 >        final PublicSemaphore lock = new PublicSemaphore(1, fair);
370 >        assertTrue(lock.getQueuedThreads().isEmpty());
371 >        lock.acquireUninterruptibly();
372 >        assertTrue(lock.getQueuedThreads().isEmpty());
373 >        Thread t1 = newStartedThread(new InterruptedLockRunnable(lock));
374 >        waitForQueuedThread(lock, t1);
375 >        assertTrue(lock.getQueuedThreads().contains(t1));
376 >        Thread t2 = newStartedThread(new InterruptibleLockRunnable(lock));
377 >        waitForQueuedThread(lock, t2);
378 >        assertTrue(lock.getQueuedThreads().contains(t1));
379 >        assertTrue(lock.getQueuedThreads().contains(t2));
380 >        t1.interrupt();
381 >        awaitTermination(t1);
382 >        assertFalse(lock.getQueuedThreads().contains(t1));
383 >        assertTrue(lock.getQueuedThreads().contains(t2));
384 >        lock.release();
385 >        awaitTermination(t2);
386 >        assertTrue(lock.getQueuedThreads().isEmpty());
387 >    }
388  
389      /**
390       * drainPermits reports and removes given number of permits
391       */
392 <    public void testDrainPermits() {
393 <        Semaphore s = new Semaphore(0, false);
392 >    public void testDrainPermits()      { testDrainPermits(false); }
393 >    public void testDrainPermits_fair() { testDrainPermits(true); }
394 >    public void testDrainPermits(boolean fair) {
395 >        Semaphore s = new Semaphore(0, fair);
396          assertEquals(0, s.availablePermits());
397          assertEquals(0, s.drainPermits());
398          s.release(10);
# Line 412 | Line 403 | public class SemaphoreTest extends JSR16
403      }
404  
405      /**
406 <     * reducePermits reduces number of permits
406 >     * release(-N) throws IllegalArgumentException
407       */
408 <    public void testReducePermits() {
409 <        PublicSemaphore s = new PublicSemaphore(10, false);
410 <        assertEquals(10, s.availablePermits());
411 <        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);
408 >    public void testReleaseIAE()      { testReleaseIAE(false); }
409 >    public void testReleaseIAE_fair() { testReleaseIAE(true); }
410 >    public void testReleaseIAE(boolean fair) {
411 >        Semaphore s = new Semaphore(10, fair);
412          try {
413 <            l.acquire();
414 <            l.release();
415 <            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 <        }
449 <    }
450 <
451 <
452 <    /**
453 <     * Zero, negative, and positive initial values are allowed in constructor
454 <     */
455 <    public void testConstructor_fair() {
456 <        Semaphore s0 = new Semaphore(0, true);
457 <        assertEquals(0, s0.availablePermits());
458 <        assertTrue(s0.isFair());
459 <        Semaphore s1 = new Semaphore(-1, true);
460 <        assertEquals(-1, s1.availablePermits());
461 <        Semaphore s2 = new Semaphore(-1, true);
462 <        assertEquals(-1, s2.availablePermits());
413 >            s.release(-1);
414 >            shouldThrow();
415 >        } catch (IllegalArgumentException success) {}
416      }
417  
418      /**
419 <     * tryAcquire succeeds when sufficient permits, else fails
419 >     * reducePermits(-N) throws IllegalArgumentException
420       */
421 <    public void testTryAcquireInSameThread_fair() {
422 <        Semaphore s = new Semaphore(2, true);
423 <        assertEquals(2, s.availablePermits());
424 <        assertTrue(s.tryAcquire());
425 <        assertTrue(s.tryAcquire());
426 <        assertEquals(0, s.availablePermits());
427 <        assertFalse(s.tryAcquire());
421 >    public void testReducePermitsIAE()      { testReducePermitsIAE(false); }
422 >    public void testReducePermitsIAE_fair() { testReducePermitsIAE(true); }
423 >    public void testReducePermitsIAE(boolean fair) {
424 >        PublicSemaphore s = new PublicSemaphore(10, fair);
425 >        try {
426 >            s.reducePermits(-1);
427 >            shouldThrow();
428 >        } catch (IllegalArgumentException success) {}
429      }
430  
431      /**
432 <     * tryAcquire(n) succeeds when sufficient permits, else fails
432 >     * reducePermits reduces number of permits
433       */
434 <    public void testTryAcquireNInSameThread_fair() {
435 <        Semaphore s = new Semaphore(2, true);
436 <        assertEquals(2, s.availablePermits());
437 <        assertTrue(s.tryAcquire(2));
438 <        assertEquals(0, s.availablePermits());
439 <        assertFalse(s.tryAcquire());
434 >    public void testReducePermits()      { testReducePermits(false); }
435 >    public void testReducePermits_fair() { testReducePermits(true); }
436 >    public void testReducePermits(boolean fair) {
437 >        PublicSemaphore s = new PublicSemaphore(10, fair);
438 >        assertEquals(10, s.availablePermits());
439 >        s.reducePermits(0);
440 >        assertEquals(10, s.availablePermits());
441 >        s.reducePermits(1);
442 >        assertEquals(9, s.availablePermits());
443 >        s.reducePermits(10);
444 >        assertEquals(-1, s.availablePermits());
445 >        s.reducePermits(10);
446 >        assertEquals(-11, s.availablePermits());
447 >        s.reducePermits(0);
448 >        assertEquals(-11, s.availablePermits());
449      }
450  
451      /**
452 <     * Acquire and release of semaphore succeed if initially available
452 >     * a reserialized semaphore has same number of permits and
453 >     * fairness, but no queued threads
454       */
455 <    public void testAcquireReleaseInSameThread_fair() {
456 <        Semaphore s = new Semaphore(1, true);
455 >    public void testSerialization()      { testSerialization(false); }
456 >    public void testSerialization_fair() { testSerialization(true); }
457 >    public void testSerialization(boolean fair) {
458          try {
459 +            Semaphore s = new Semaphore(3, fair);
460              s.acquire();
495            s.release();
461              s.acquire();
462              s.release();
498            s.acquire();
499            s.release();
500            s.acquire();
501            s.release();
502            s.acquire();
503            s.release();
504            assertEquals(1, s.availablePermits());
505        } catch( InterruptedException e){
506            unexpectedException();
507        }
508    }
509
510    /**
511     * Acquire(n) and release(n) of semaphore succeed if initially available
512     */
513    public void testAcquireReleaseNInSameThread_fair() {
514        Semaphore s = new Semaphore(1, true);
515        try {
516            s.release(1);
517            s.acquire(1);
518            s.release(2);
519            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    }
463  
464 <    /**
465 <     * Acquire(n) and release(n) of semaphore succeed if initially available
466 <     */
467 <    public void testAcquireUninterruptiblyReleaseNInSameThread_fair() {
468 <        Semaphore s = new Semaphore(1, true);
469 <        try {
470 <            s.release(1);
471 <            s.acquireUninterruptibly(1);
472 <            s.release(2);
473 <            s.acquireUninterruptibly(2);
474 <            s.release(3);
475 <            s.acquireUninterruptibly(3);
476 <            s.release(4);
477 <            s.acquireUninterruptibly(4);
478 <            s.release(5);
479 <            s.acquireUninterruptibly(5);
480 <            assertEquals(1, s.availablePermits());
481 <        } finally {
464 >            Semaphore clone = serialClone(s);
465 >            assertEquals(fair, s.isFair());
466 >            assertEquals(fair, clone.isFair());
467 >            assertEquals(2, s.availablePermits());
468 >            assertEquals(2, clone.availablePermits());
469 >            clone.acquire();
470 >            clone.acquire();
471 >            clone.release();
472 >            assertEquals(2, s.availablePermits());
473 >            assertEquals(1, clone.availablePermits());
474 >            assertFalse(s.hasQueuedThreads());
475 >            assertFalse(clone.hasQueuedThreads());
476 >        } catch (InterruptedException e) { threadUnexpectedException(e); }
477 >
478 >        {
479 >            PublicSemaphore s = new PublicSemaphore(0, fair);
480 >            Thread t = newStartedThread(new InterruptibleLockRunnable(s));
481 >            // waitForQueuedThreads(s); // suffers from "flicker", so ...
482 >            waitForQueuedThread(s, t);  // ... we use this instead
483 >            PublicSemaphore clone = serialClone(s);
484 >            assertEquals(fair, s.isFair());
485 >            assertEquals(fair, clone.isFair());
486 >            assertEquals(0, s.availablePermits());
487 >            assertEquals(0, clone.availablePermits());
488 >            assertTrue(s.hasQueuedThreads());
489 >            assertFalse(clone.hasQueuedThreads());
490 >            s.release();
491 >            awaitTermination(t);
492 >            assertFalse(s.hasQueuedThreads());
493 >            assertFalse(clone.hasQueuedThreads());
494          }
495      }
496  
497      /**
498 <     * release(n) in one thread enables timed acquire(n) in another thread
498 >     * tryAcquire(n) succeeds when sufficient permits, else fails
499       */
500 <    public void testTimedAcquireReleaseNInSameThread_fair() {
501 <        Semaphore s = new Semaphore(1, true);
502 <        try {
503 <            s.release(1);
504 <            assertTrue(s.tryAcquire(1, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
505 <            s.release(2);
506 <            assertTrue(s.tryAcquire(2, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
507 <            s.release(3);
508 <            assertTrue(s.tryAcquire(3, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
509 <            s.release(4);
510 <            assertTrue(s.tryAcquire(4, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
511 <            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 <        }
500 >    public void testTryAcquireNInSameThread()      { testTryAcquireNInSameThread(false); }
501 >    public void testTryAcquireNInSameThread_fair() { testTryAcquireNInSameThread(true); }
502 >    public void testTryAcquireNInSameThread(boolean fair) {
503 >        Semaphore s = new Semaphore(2, fair);
504 >        assertEquals(2, s.availablePermits());
505 >        assertFalse(s.tryAcquire(3));
506 >        assertEquals(2, s.availablePermits());
507 >        assertTrue(s.tryAcquire(2));
508 >        assertEquals(0, s.availablePermits());
509 >        assertFalse(s.tryAcquire(1));
510 >        assertFalse(s.tryAcquire(2));
511 >        assertEquals(0, s.availablePermits());
512      }
513  
514      /**
515 <     * release in one thread enables timed acquire in another thread
515 >     * acquire succeeds if permits available
516       */
517 <    public void testTimedAcquireReleaseInSameThread_fair() {
518 <        Semaphore s = new Semaphore(1, true);
519 <        try {
520 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
521 <            s.release();
522 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
523 <            s.release();
524 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
525 <            s.release();
526 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
527 <            s.release();
528 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
529 <            s.release();
517 >    public void testReleaseAcquireSameThread_acquire()       { testReleaseAcquireSameThread(false, AcquireMethod.acquire); }
518 >    public void testReleaseAcquireSameThread_acquire_fair()  { testReleaseAcquireSameThread(true, AcquireMethod.acquire); }
519 >    public void testReleaseAcquireSameThread_acquireN()      { testReleaseAcquireSameThread(false, AcquireMethod.acquireN); }
520 >    public void testReleaseAcquireSameThread_acquireN_fair() { testReleaseAcquireSameThread(true, AcquireMethod.acquireN); }
521 >    public void testReleaseAcquireSameThread_acquireUninterruptibly()       { testReleaseAcquireSameThread(false, AcquireMethod.acquireUninterruptibly); }
522 >    public void testReleaseAcquireSameThread_acquireUninterruptibly_fair()  { testReleaseAcquireSameThread(true, AcquireMethod.acquireUninterruptibly); }
523 >    public void testReleaseAcquireSameThread_acquireUninterruptiblyN()      { testReleaseAcquireSameThread(false, AcquireMethod.acquireUninterruptibly); }
524 >    public void testReleaseAcquireSameThread_acquireUninterruptiblyN_fair() { testReleaseAcquireSameThread(true, AcquireMethod.acquireUninterruptibly); }
525 >    public void testReleaseAcquireSameThread_tryAcquire()       { testReleaseAcquireSameThread(false, AcquireMethod.tryAcquire); }
526 >    public void testReleaseAcquireSameThread_tryAcquire_fair()  { testReleaseAcquireSameThread(true, AcquireMethod.tryAcquire); }
527 >    public void testReleaseAcquireSameThread_tryAcquireN()      { testReleaseAcquireSameThread(false, AcquireMethod.tryAcquireN); }
528 >    public void testReleaseAcquireSameThread_tryAcquireN_fair() { testReleaseAcquireSameThread(true, AcquireMethod.tryAcquireN); }
529 >    public void testReleaseAcquireSameThread_tryAcquireTimed()       { testReleaseAcquireSameThread(false, AcquireMethod.tryAcquireTimed); }
530 >    public void testReleaseAcquireSameThread_tryAcquireTimed_fair()  { testReleaseAcquireSameThread(true, AcquireMethod.tryAcquireTimed); }
531 >    public void testReleaseAcquireSameThread_tryAcquireTimedN()      { testReleaseAcquireSameThread(false, AcquireMethod.tryAcquireTimedN); }
532 >    public void testReleaseAcquireSameThread_tryAcquireTimedN_fair() { testReleaseAcquireSameThread(true, AcquireMethod.tryAcquireTimedN); }
533 >    public void testReleaseAcquireSameThread(boolean fair,
534 >                                             final AcquireMethod acquirer) {
535 >        Semaphore s = new Semaphore(1, fair);
536 >        for (int i = 1; i < 6; i++) {
537 >            s.release(i);
538 >            assertEquals(1 + i, s.availablePermits());
539 >            try {
540 >                acquirer.acquire(s, i);
541 >            } catch (InterruptedException e) { threadUnexpectedException(e); }
542              assertEquals(1, s.availablePermits());
592        } catch( InterruptedException e){
593            unexpectedException();
543          }
544      }
545  
546      /**
547 <     * A release in one thread enables an acquire in another thread
547 >     * release in one thread enables acquire in another thread
548       */
549 <    public void testAcquireReleaseInDifferentThreads_fair() {
550 <        final Semaphore s = new Semaphore(0, true);
551 <        Thread t = new Thread(new Runnable() {
552 <                public void run() {
553 <                    try {
554 <                        s.acquire();
555 <                        s.acquire();
556 <                        s.acquire();
557 <                        s.acquire();
558 <                    } catch(InterruptedException ie){
559 <                        threadUnexpectedException();
560 <                    }
561 <                }
562 <            });
563 <        try {
564 <            t.start();
565 <            Thread.sleep(SHORT_DELAY_MS);
566 <            s.release();
567 <            s.release();
568 <            s.release();
569 <            s.release();
570 <            s.release();
571 <            s.release();
572 <            t.join();
573 <            assertEquals(2, s.availablePermits());
574 <        } catch( InterruptedException e){
575 <            unexpectedException();
576 <        }
577 <    }
578 <
579 <    /**
580 <     * release(n) in one thread enables acquire(n) in another thread
581 <     */
582 <    public void testAcquireReleaseNInDifferentThreads_fair() {
583 <        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();
549 >    public void testReleaseAcquireDifferentThreads_acquire()       { testReleaseAcquireDifferentThreads(false, AcquireMethod.acquire); }
550 >    public void testReleaseAcquireDifferentThreads_acquire_fair()  { testReleaseAcquireDifferentThreads(true, AcquireMethod.acquire); }
551 >    public void testReleaseAcquireDifferentThreads_acquireN()      { testReleaseAcquireDifferentThreads(false, AcquireMethod.acquireN); }
552 >    public void testReleaseAcquireDifferentThreads_acquireN_fair() { testReleaseAcquireDifferentThreads(true, AcquireMethod.acquireN); }
553 >    public void testReleaseAcquireDifferentThreads_acquireUninterruptibly()       { testReleaseAcquireDifferentThreads(false, AcquireMethod.acquireUninterruptibly); }
554 >    public void testReleaseAcquireDifferentThreads_acquireUninterruptibly_fair()  { testReleaseAcquireDifferentThreads(true, AcquireMethod.acquireUninterruptibly); }
555 >    public void testReleaseAcquireDifferentThreads_acquireUninterruptiblyN()      { testReleaseAcquireDifferentThreads(false, AcquireMethod.acquireUninterruptibly); }
556 >    public void testReleaseAcquireDifferentThreads_acquireUninterruptiblyN_fair() { testReleaseAcquireDifferentThreads(true, AcquireMethod.acquireUninterruptibly); }
557 >    public void testReleaseAcquireDifferentThreads_tryAcquireTimed()       { testReleaseAcquireDifferentThreads(false, AcquireMethod.tryAcquireTimed); }
558 >    public void testReleaseAcquireDifferentThreads_tryAcquireTimed_fair()  { testReleaseAcquireDifferentThreads(true, AcquireMethod.tryAcquireTimed); }
559 >    public void testReleaseAcquireDifferentThreads_tryAcquireTimedN()      { testReleaseAcquireDifferentThreads(false, AcquireMethod.tryAcquireTimedN); }
560 >    public void testReleaseAcquireDifferentThreads_tryAcquireTimedN_fair() { testReleaseAcquireDifferentThreads(true, AcquireMethod.tryAcquireTimedN); }
561 >    public void testReleaseAcquireDifferentThreads(boolean fair,
562 >                                                   final AcquireMethod acquirer) {
563 >        final Semaphore s = new Semaphore(0, fair);
564 >        final int rounds = 4;
565 >        long startTime = System.nanoTime();
566 >        Thread t = newStartedThread(new CheckedRunnable() {
567 >            public void realRun() throws InterruptedException {
568 >                for (int i = 0; i < rounds; i++) {
569 >                    assertFalse(s.hasQueuedThreads());
570 >                    if (i % 2 == 0)
571 >                        acquirer.acquire(s);
572 >                    else
573 >                        acquirer.acquire(s, 3);
574 >                }}});
575 >
576 >        for (int i = 0; i < rounds; i++) {
577 >            while (! (s.availablePermits() == 0 && s.hasQueuedThreads()))
578 >                Thread.yield();
579 >            assertTrue(t.isAlive());
580 >            if (i % 2 == 0)
581 >                s.release();
582 >            else
583 >                s.release(3);
584          }
585 +        awaitTermination(t);
586 +        assertEquals(0, s.availablePermits());
587 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
588      }
589  
590      /**
591 <     * 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();
872 <        }
873 <    }
874 <
875 <
876 <    /**
877 <     * a deserialized serialized semaphore has same number of permits
591 >     * fair locks are strictly FIFO
592       */
593 <    public void testSerialization_fair() {
594 <        Semaphore l = new Semaphore(3, true);
595 <
596 <        try {
597 <            l.acquire();
598 <            l.release();
599 <            ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
600 <            ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
601 <            out.writeObject(l);
602 <            out.close();
603 <
604 <            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
605 <            ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
606 <            Semaphore r = (Semaphore) in.readObject();
607 <            assertEquals(3, r.availablePermits());
608 <            assertTrue(r.isFair());
609 <            r.acquire();
610 <            r.release();
611 <        } catch(Exception e){
612 <            unexpectedException();
613 <        }
593 >    public void testFairLocksFifo() {
594 >        final PublicSemaphore s = new PublicSemaphore(1, true);
595 >        final CountDownLatch pleaseRelease = new CountDownLatch(1);
596 >        Thread t1 = newStartedThread(new CheckedRunnable() {
597 >            public void realRun() throws InterruptedException {
598 >                // Will block; permits are available, but not three
599 >                s.acquire(3);
600 >            }});
601 >
602 >        waitForQueuedThread(s, t1);
603 >
604 >        Thread t2 = newStartedThread(new CheckedRunnable() {
605 >            public void realRun() throws InterruptedException {
606 >                // Will fail, even though 1 permit is available
607 >                assertFalse(
608 >                    s.tryAcquire(randomExpiredTimeout(), randomTimeUnit()));
609 >                assertFalse(
610 >                    s.tryAcquire(1, randomExpiredTimeout(), randomTimeUnit()));
611 >
612 >                // untimed tryAcquire will barge and succeed
613 >                assertTrue(s.tryAcquire());
614 >                s.release(2);
615 >                assertTrue(s.tryAcquire(2));
616 >                s.release();
617 >
618 >                pleaseRelease.countDown();
619 >                // Will queue up behind t1, even though 1 permit is available
620 >                s.acquire();
621 >            }});
622 >
623 >        await(pleaseRelease);
624 >        waitForQueuedThread(s, t2);
625 >        s.release(2);
626 >        awaitTermination(t1);
627 >        assertTrue(t2.isAlive());
628 >        s.release();
629 >        awaitTermination(t2);
630      }
631  
632      /**
633       * toString indicates current number of permits
634       */
635 <    public void testToString() {
636 <        Semaphore s = new Semaphore(0);
637 <        String us = s.toString();
638 <        assertTrue(us.indexOf("Permits = 0") >= 0);
639 <        s.release();
910 <        String s1 = s.toString();
911 <        assertTrue(s1.indexOf("Permits = 1") >= 0);
635 >    public void testToString()      { testToString(false); }
636 >    public void testToString_fair() { testToString(true); }
637 >    public void testToString(boolean fair) {
638 >        PublicSemaphore s = new PublicSemaphore(0, fair);
639 >        assertTrue(s.toString().contains("Permits = 0"));
640          s.release();
641 <        String s2 = s.toString();
642 <        assertTrue(s2.indexOf("Permits = 2") >= 0);
641 >        assertTrue(s.toString().contains("Permits = 1"));
642 >        s.release(2);
643 >        assertTrue(s.toString().contains("Permits = 3"));
644 >        s.reducePermits(5);
645 >        assertTrue(s.toString().contains("Permits = -2"));
646      }
647  
648   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines