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.12 by dl, Sun Jan 4 22:58:03 2004 UTC vs.
Revision 1.30 by jsr166, Fri Jun 3 05:07:14 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
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.*;
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); }
28 <        public Collection<Thread> getQueuedThreads() {
29 <            return super.getQueuedThreads();
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 <        Semaphore s2 = new Semaphore(-1, false);
74 <        assertEquals(-1, s2.availablePermits());
75 <    }
76 <
77 <    /**
78 <     * tryAcquire succeeds when sufficient permits, else fails
79 <     */
80 <    public void testTryAcquireInSameThread() {
81 <        Semaphore s = new Semaphore(2, false);
82 <        assertEquals(2, s.availablePermits());
83 <        assertTrue(s.tryAcquire());
84 <        assertTrue(s.tryAcquire());
85 <        assertEquals(0, s.availablePermits());
86 <        assertFalse(s.tryAcquire());
87 <    }
88 <
89 <    /**
90 <     * Acquire and release of semaphore succeed if initially available
91 <     */
92 <    public void testAcquireReleaseInSameThread() {
93 <        Semaphore s = new Semaphore(1, false);
94 <        try {
95 <            s.acquire();
96 <            s.release();
97 <            s.acquire();
98 <            s.release();
99 <            s.acquire();
100 <            s.release();
101 <            s.acquire();
102 <            s.release();
103 <            s.acquire();
104 <            s.release();
105 <            assertEquals(1, s.availablePermits());
106 <        } catch( InterruptedException e){
107 <            unexpectedException();
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 <     * Uninterruptible acquire and release of semaphore succeed if
113 <     * initially available
160 >     * Constructor without fairness argument behaves as nonfair
161       */
162 <    public void testAcquireUninterruptiblyReleaseInSameThread() {
163 <        Semaphore s = new Semaphore(1, false);
164 <        try {
165 <            s.acquireUninterruptibly();
166 <            s.release();
120 <            s.acquireUninterruptibly();
121 <            s.release();
122 <            s.acquireUninterruptibly();
123 <            s.release();
124 <            s.acquireUninterruptibly();
125 <            s.release();
126 <            s.acquireUninterruptibly();
127 <            s.release();
128 <            assertEquals(1, s.availablePermits());
129 <        } finally {
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 <     * Timed Acquire and release of semaphore succeed if
135 <     * initially available
136 <     */
137 <    public void testTimedAcquireReleaseInSameThread() {
138 <        Semaphore s = new Semaphore(1, false);
139 <        try {
140 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
141 <            s.release();
142 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
143 <            s.release();
144 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
145 <            s.release();
146 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
147 <            s.release();
148 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
149 <            s.release();
150 <            assertEquals(1, s.availablePermits());
151 <        } catch( InterruptedException e){
152 <            unexpectedException();
153 <        }
154 <    }
155 <
156 <    /**
157 <     * A release in one thread enables an acquire in another thread
171 >     * tryAcquire succeeds when sufficient permits, else fails
172       */
173 <    public void testAcquireReleaseInDifferentThreads() {
174 <        final Semaphore s = new Semaphore(0, false);
175 <        Thread t = new Thread(new Runnable() {
176 <                public void run() {
177 <                    try {
178 <                        s.acquire();
179 <                        s.release();
180 <                        s.release();
181 <                        s.acquire();
182 <                    } catch(InterruptedException ie){
183 <                        threadUnexpectedException();
170 <                    }
171 <                }
172 <            });
173 <        try {
174 <            t.start();
175 <            Thread.sleep(SHORT_DELAY_MS);
176 <            s.release();
177 <            s.release();
178 <            s.acquire();
179 <            s.acquire();
180 <            s.release();
181 <            t.join();
182 <        } catch( InterruptedException e){
183 <            unexpectedException();
184 <        }
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 <     * 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 pleaseInterrupt = 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 >                pleaseInterrupt.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 >        await(pleaseInterrupt);
261 >        waitForQueuedThread(s, t);
262 >        t.interrupt();
263 >        awaitTermination(t);
264 >    }
265 >
266 >    /**
267 >     * acquireUninterruptibly(), acquireUninterruptibly(N) are
268 >     * uninterruptible
269 >     */
270 >    public void testUninterruptible_acquireUninterruptibly()       { testUninterruptible(false, AcquireMethod.acquireUninterruptibly); }
271 >    public void testUninterruptible_acquireUninterruptibly_fair()  { testUninterruptible(true,  AcquireMethod.acquireUninterruptibly); }
272 >    public void testUninterruptible_acquireUninterruptiblyN()      { testUninterruptible(false, AcquireMethod.acquireUninterruptiblyN); }
273 >    public void testUninterruptible_acquireUninterruptiblyN_fair() { testUninterruptible(true,  AcquireMethod.acquireUninterruptiblyN); }
274 >    public void testUninterruptible(boolean fair, final AcquireMethod acquirer) {
275 >        final PublicSemaphore s = new PublicSemaphore(0, fair);
276 >        final Semaphore pleaseInterrupt = new Semaphore(-1, fair);
277 >
278 >        Thread t1 = newStartedThread(new CheckedRunnable() {
279 >            public void realRun() throws InterruptedException {
280 >                // Interrupt before acquire
281 >                pleaseInterrupt.release();
282 >                Thread.currentThread().interrupt();
283 >                acquirer.acquire(s);
284 >                assertTrue(Thread.interrupted());
285 >            }});
286 >
287 >        Thread t2 = newStartedThread(new CheckedRunnable() {
288 >            public void realRun() throws InterruptedException {
289 >                // Interrupt during acquire
290 >                pleaseInterrupt.release();
291 >                acquirer.acquire(s);
292 >                assertTrue(Thread.interrupted());
293 >            }});
294 >
295 >        await(pleaseInterrupt);
296 >        waitForQueuedThread(s, t1);
297 >        waitForQueuedThread(s, t2);
298 >        t2.interrupt();
299  
300 +        assertThreadStaysAlive(t1);
301 +        assertTrue(t2.isAlive());
302  
303 <    /**
216 <     *  A release in one thread enables a timed acquire in another thread
217 <     */
218 <    public void testTimedAcquireReleaseInDifferentThreads() {
219 <        final Semaphore s = new Semaphore(1, false);
220 <        Thread t = new Thread(new Runnable() {
221 <                public void run() {
222 <                    try {
223 <                        s.release();
224 <                        threadAssertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
225 <                        s.release();
226 <                        threadAssertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
303 >        s.release(2);
304  
305 <                    } catch(InterruptedException ie){
306 <                        threadUnexpectedException();
230 <                    }
231 <                }
232 <            });
233 <        try {
234 <            t.start();
235 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
236 <            s.release();
237 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
238 <            s.release();
239 <            s.release();
240 <            t.join();
241 <        } catch( InterruptedException e){
242 <            unexpectedException();
243 <        }
244 <    }
245 <
246 <    /**
247 <     * A waiting acquire blocks interruptibly
248 <     */
249 <    public void testAcquire_InterruptedException() {
250 <        final Semaphore s = new Semaphore(0, false);
251 <        Thread t = new Thread(new Runnable() {
252 <                public void run() {
253 <                    try {
254 <                        s.acquire();
255 <                        threadShouldThrow();
256 <                    } catch(InterruptedException success){}
257 <                }
258 <            });
259 <        t.start();
260 <        try {
261 <            Thread.sleep(SHORT_DELAY_MS);
262 <            t.interrupt();
263 <            t.join();
264 <        } catch(InterruptedException e){
265 <            unexpectedException();
266 <        }
267 <    }
268 <    
269 <    /**
270 <     *  A waiting timed acquire blocks interruptibly
271 <     */
272 <    public void testTryAcquire_InterruptedException() {
273 <        final Semaphore s = new Semaphore(0, false);
274 <        Thread t = new Thread(new Runnable() {
275 <                public void run() {
276 <                    try {
277 <                        s.tryAcquire(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
278 <                        threadShouldThrow();
279 <                    } catch(InterruptedException success){
280 <                    }
281 <                }
282 <            });
283 <        t.start();
284 <        try {
285 <            Thread.sleep(SHORT_DELAY_MS);
286 <            t.interrupt();
287 <            t.join();
288 <        } catch(InterruptedException e){
289 <            unexpectedException();
290 <        }
305 >        awaitTermination(t1);
306 >        awaitTermination(t2);
307      }
308  
309      /**
310       * hasQueuedThreads reports whether there are waiting threads
311       */
312 <    public void testHasQueuedThreads() {
313 <        final Semaphore lock = new Semaphore(1, false);
314 <        Thread t1 = new Thread(new InterruptedLockRunnable(lock));
315 <        Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
316 <        try {
317 <            assertFalse(lock.hasQueuedThreads());
318 <            lock.acquireUninterruptibly();
319 <            t1.start();
320 <            Thread.sleep(SHORT_DELAY_MS);
321 <            assertTrue(lock.hasQueuedThreads());
322 <            t2.start();
323 <            Thread.sleep(SHORT_DELAY_MS);
324 <            assertTrue(lock.hasQueuedThreads());
325 <            t1.interrupt();
326 <            Thread.sleep(SHORT_DELAY_MS);
327 <            assertTrue(lock.hasQueuedThreads());
328 <            lock.release();
329 <            Thread.sleep(SHORT_DELAY_MS);
330 <            assertFalse(lock.hasQueuedThreads());
315 <            t1.join();
316 <            t2.join();
317 <        } catch(Exception e){
318 <            unexpectedException();
319 <        }
320 <    }
312 >    public void testHasQueuedThreads()      { testHasQueuedThreads(false); }
313 >    public void testHasQueuedThreads_fair() { testHasQueuedThreads(true); }
314 >    public void testHasQueuedThreads(boolean fair) {
315 >        final PublicSemaphore lock = new PublicSemaphore(1, fair);
316 >        assertFalse(lock.hasQueuedThreads());
317 >        lock.acquireUninterruptibly();
318 >        Thread t1 = newStartedThread(new InterruptedLockRunnable(lock));
319 >        waitForQueuedThread(lock, t1);
320 >        assertTrue(lock.hasQueuedThreads());
321 >        Thread t2 = newStartedThread(new InterruptibleLockRunnable(lock));
322 >        waitForQueuedThread(lock, t2);
323 >        assertTrue(lock.hasQueuedThreads());
324 >        t1.interrupt();
325 >        awaitTermination(t1);
326 >        assertTrue(lock.hasQueuedThreads());
327 >        lock.release();
328 >        awaitTermination(t2);
329 >        assertFalse(lock.hasQueuedThreads());
330 >    }
331  
332      /**
333       * getQueueLength reports number of waiting threads
334       */
335 <    public void testGetQueueLength() {
336 <        final Semaphore lock = new Semaphore(1, false);
337 <        Thread t1 = new Thread(new InterruptedLockRunnable(lock));
338 <        Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
339 <        try {
340 <            assertEquals(0, lock.getQueueLength());
341 <            lock.acquireUninterruptibly();
342 <            t1.start();
343 <            Thread.sleep(SHORT_DELAY_MS);
344 <            assertEquals(1, lock.getQueueLength());
345 <            t2.start();
346 <            Thread.sleep(SHORT_DELAY_MS);
347 <            assertEquals(2, lock.getQueueLength());
348 <            t1.interrupt();
349 <            Thread.sleep(SHORT_DELAY_MS);
350 <            assertEquals(1, lock.getQueueLength());
351 <            lock.release();
352 <            Thread.sleep(SHORT_DELAY_MS);
353 <            assertEquals(0, lock.getQueueLength());
344 <            t1.join();
345 <            t2.join();
346 <        } catch(Exception e){
347 <            unexpectedException();
348 <        }
349 <    }
335 >    public void testGetQueueLength()      { testGetQueueLength(false); }
336 >    public void testGetQueueLength_fair() { testGetQueueLength(true); }
337 >    public void testGetQueueLength(boolean fair) {
338 >        final PublicSemaphore lock = new PublicSemaphore(1, fair);
339 >        assertEquals(0, lock.getQueueLength());
340 >        lock.acquireUninterruptibly();
341 >        Thread t1 = newStartedThread(new InterruptedLockRunnable(lock));
342 >        waitForQueuedThread(lock, t1);
343 >        assertEquals(1, lock.getQueueLength());
344 >        Thread t2 = newStartedThread(new InterruptibleLockRunnable(lock));
345 >        waitForQueuedThread(lock, t2);
346 >        assertEquals(2, lock.getQueueLength());
347 >        t1.interrupt();
348 >        awaitTermination(t1);
349 >        assertEquals(1, lock.getQueueLength());
350 >        lock.release();
351 >        awaitTermination(t2);
352 >        assertEquals(0, lock.getQueueLength());
353 >    }
354  
355      /**
356       * getQueuedThreads includes waiting threads
357       */
358 <    public void testGetQueuedThreads() {
359 <        final PublicSemaphore lock = new PublicSemaphore(1, false);
360 <        Thread t1 = new Thread(new InterruptedLockRunnable(lock));
361 <        Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
362 <        try {
363 <            assertTrue(lock.getQueuedThreads().isEmpty());
364 <            lock.acquireUninterruptibly();
365 <            assertTrue(lock.getQueuedThreads().isEmpty());
366 <            t1.start();
367 <            Thread.sleep(SHORT_DELAY_MS);
368 <            assertTrue(lock.getQueuedThreads().contains(t1));
369 <            t2.start();
370 <            Thread.sleep(SHORT_DELAY_MS);
371 <            assertTrue(lock.getQueuedThreads().contains(t1));
372 <            assertTrue(lock.getQueuedThreads().contains(t2));
373 <            t1.interrupt();
374 <            Thread.sleep(SHORT_DELAY_MS);
375 <            assertFalse(lock.getQueuedThreads().contains(t1));
376 <            assertTrue(lock.getQueuedThreads().contains(t2));
377 <            lock.release();
378 <            Thread.sleep(SHORT_DELAY_MS);
379 <            assertTrue(lock.getQueuedThreads().isEmpty());
376 <            t1.join();
377 <            t2.join();
378 <        } catch(Exception e){
379 <            unexpectedException();
380 <        }
381 <    }
358 >    public void testGetQueuedThreads()      { testGetQueuedThreads(false); }
359 >    public void testGetQueuedThreads_fair() { testGetQueuedThreads(true); }
360 >    public void testGetQueuedThreads(boolean fair) {
361 >        final PublicSemaphore lock = new PublicSemaphore(1, fair);
362 >        assertTrue(lock.getQueuedThreads().isEmpty());
363 >        lock.acquireUninterruptibly();
364 >        assertTrue(lock.getQueuedThreads().isEmpty());
365 >        Thread t1 = newStartedThread(new InterruptedLockRunnable(lock));
366 >        waitForQueuedThread(lock, t1);
367 >        assertTrue(lock.getQueuedThreads().contains(t1));
368 >        Thread t2 = newStartedThread(new InterruptibleLockRunnable(lock));
369 >        waitForQueuedThread(lock, t2);
370 >        assertTrue(lock.getQueuedThreads().contains(t1));
371 >        assertTrue(lock.getQueuedThreads().contains(t2));
372 >        t1.interrupt();
373 >        awaitTermination(t1);
374 >        assertFalse(lock.getQueuedThreads().contains(t1));
375 >        assertTrue(lock.getQueuedThreads().contains(t2));
376 >        lock.release();
377 >        awaitTermination(t2);
378 >        assertTrue(lock.getQueuedThreads().isEmpty());
379 >    }
380  
381      /**
382       * drainPermits reports and removes given number of permits
383       */
384 <    public void testDrainPermits() {
385 <        Semaphore s = new Semaphore(0, false);
384 >    public void testDrainPermits()      { testDrainPermits(false); }
385 >    public void testDrainPermits_fair() { testDrainPermits(true); }
386 >    public void testDrainPermits(boolean fair) {
387 >        Semaphore s = new Semaphore(0, fair);
388          assertEquals(0, s.availablePermits());
389          assertEquals(0, s.drainPermits());
390          s.release(10);
# Line 395 | Line 395 | public class SemaphoreTest extends JSR16
395      }
396  
397      /**
398 <     * reducePermits reduces number of permits
398 >     * release(-N) throws IllegalArgumentException
399       */
400 <    public void testReducePermits() {
401 <        PublicSemaphore s = new PublicSemaphore(10, false);
402 <        assertEquals(10, s.availablePermits());
403 <        s.reducePermits(1);
404 <        assertEquals(9, s.availablePermits());
405 <        s.reducePermits(10);
406 <        assertEquals(-1, s.availablePermits());
407 <    }
408 <
409 <    /**
410 <     * a deserialized serialized semaphore has same number of permits
411 <     */
412 <    public void testSerialization() {
413 <        Semaphore l = new Semaphore(3, false);
400 >    public void testReleaseIAE()      { testReleaseIAE(false); }
401 >    public void testReleaseIAE_fair() { testReleaseIAE(true); }
402 >    public void testReleaseIAE(boolean fair) {
403 >        Semaphore s = new Semaphore(10, fair);
404          try {
405 <            l.acquire();
406 <            l.release();
407 <            ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
418 <            ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
419 <            out.writeObject(l);
420 <            out.close();
421 <
422 <            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
423 <            ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
424 <            Semaphore r = (Semaphore) in.readObject();
425 <            assertEquals(3, r.availablePermits());
426 <            assertFalse(r.isFair());
427 <            r.acquire();
428 <            r.release();
429 <        } catch(Exception e){
430 <            unexpectedException();
431 <        }
405 >            s.release(-1);
406 >            shouldThrow();
407 >        } catch (IllegalArgumentException success) {}
408      }
409  
434
410      /**
411 <     * Zero, negative, and positive initial values are allowed in constructor
411 >     * reducePermits(-N) throws IllegalArgumentException
412       */
413 <    public void testConstructor_fair() {
414 <        Semaphore s0 = new Semaphore(0, true);
415 <        assertEquals(0, s0.availablePermits());
416 <        assertTrue(s0.isFair());
417 <        Semaphore s1 = new Semaphore(-1, true);
418 <        assertEquals(-1, s1.availablePermits());
419 <        Semaphore s2 = new Semaphore(-1, true);
420 <        assertEquals(-1, s2.availablePermits());
446 <    }
447 <
448 <    /**
449 <     * tryAcquire succeeds when sufficient permits, else fails
450 <     */
451 <    public void testTryAcquireInSameThread_fair() {
452 <        Semaphore s = new Semaphore(2, true);
453 <        assertEquals(2, s.availablePermits());
454 <        assertTrue(s.tryAcquire());
455 <        assertTrue(s.tryAcquire());
456 <        assertEquals(0, s.availablePermits());
457 <        assertFalse(s.tryAcquire());
413 >    public void testReducePermitsIAE()      { testReducePermitsIAE(false); }
414 >    public void testReducePermitsIAE_fair() { testReducePermitsIAE(true); }
415 >    public void testReducePermitsIAE(boolean fair) {
416 >        PublicSemaphore s = new PublicSemaphore(10, fair);
417 >        try {
418 >            s.reducePermits(-1);
419 >            shouldThrow();
420 >        } catch (IllegalArgumentException success) {}
421      }
422  
423      /**
424 <     * tryAcquire(n) succeeds when sufficient permits, else fails
424 >     * reducePermits reduces number of permits
425       */
426 <    public void testTryAcquireNInSameThread_fair() {
427 <        Semaphore s = new Semaphore(2, true);
428 <        assertEquals(2, s.availablePermits());
429 <        assertTrue(s.tryAcquire(2));
430 <        assertEquals(0, s.availablePermits());
431 <        assertFalse(s.tryAcquire());
426 >    public void testReducePermits()      { testReducePermits(false); }
427 >    public void testReducePermits_fair() { testReducePermits(true); }
428 >    public void testReducePermits(boolean fair) {
429 >        PublicSemaphore s = new PublicSemaphore(10, fair);
430 >        assertEquals(10, s.availablePermits());
431 >        s.reducePermits(0);
432 >        assertEquals(10, s.availablePermits());
433 >        s.reducePermits(1);
434 >        assertEquals(9, s.availablePermits());
435 >        s.reducePermits(10);
436 >        assertEquals(-1, s.availablePermits());
437 >        s.reducePermits(10);
438 >        assertEquals(-11, s.availablePermits());
439 >        s.reducePermits(0);
440 >        assertEquals(-11, s.availablePermits());
441      }
442  
443      /**
444 <     * Acquire and release of semaphore succeed if initially available
444 >     * a reserialized semaphore has same number of permits and
445 >     * fairness, but no queued threads
446       */
447 <    public void testAcquireReleaseInSameThread_fair() {
448 <        Semaphore s = new Semaphore(1, true);
447 >    public void testSerialization()      { testSerialization(false); }
448 >    public void testSerialization_fair() { testSerialization(true); }
449 >    public void testSerialization(boolean fair) {
450          try {
451 +            Semaphore s = new Semaphore(3, fair);
452              s.acquire();
478            s.release();
479            s.acquire();
480            s.release();
481            s.acquire();
482            s.release();
483            s.acquire();
484            s.release();
453              s.acquire();
454              s.release();
487            assertEquals(1, s.availablePermits());
488        } catch( InterruptedException e){
489            unexpectedException();
490        }
491    }
455  
456 <    /**
457 <     * Acquire(n) and release(n) of semaphore succeed if initially available
458 <     */
459 <    public void testAcquireReleaseNInSameThread_fair() {
460 <        Semaphore s = new Semaphore(1, true);
461 <        try {
462 <            s.release(1);
463 <            s.acquire(1);
464 <            s.release(2);
465 <            s.acquire(2);
503 <            s.release(3);
504 <            s.acquire(3);
505 <            s.release(4);
506 <            s.acquire(4);
507 <            s.release(5);
508 <            s.acquire(5);
509 <            assertEquals(1, s.availablePermits());
510 <        } catch( InterruptedException e){
511 <            unexpectedException();
512 <        }
513 <    }
456 >            Semaphore clone = serialClone(s);
457 >            assertEquals(fair, s.isFair());
458 >            assertEquals(fair, clone.isFair());
459 >            assertEquals(2, s.availablePermits());
460 >            assertEquals(2, clone.availablePermits());
461 >            clone.acquire();
462 >            clone.acquire();
463 >            clone.release();
464 >            assertEquals(2, s.availablePermits());
465 >            assertEquals(1, clone.availablePermits());
466  
467 <    /**
468 <     * Acquire(n) and release(n) of semaphore succeed if initially available
469 <     */
470 <    public void testAcquireUninterruptiblyReleaseNInSameThread_fair() {
471 <        Semaphore s = new Semaphore(1, true);
472 <        try {
473 <            s.release(1);
474 <            s.acquireUninterruptibly(1);
475 <            s.release(2);
476 <            s.acquireUninterruptibly(2);
477 <            s.release(3);
478 <            s.acquireUninterruptibly(3);
479 <            s.release(4);
480 <            s.acquireUninterruptibly(4);
481 <            s.release(5);
530 <            s.acquireUninterruptibly(5);
531 <            assertEquals(1, s.availablePermits());
532 <        } finally {
533 <        }
467 >            s = new Semaphore(0, fair);
468 >            Thread t = newStartedThread(new InterruptibleLockRunnable(s));
469 >            waitForQueuedThreads(s);
470 >            clone = serialClone(s);
471 >            assertEquals(fair, s.isFair());
472 >            assertEquals(fair, clone.isFair());
473 >            assertEquals(0, s.availablePermits());
474 >            assertEquals(0, clone.availablePermits());
475 >            assertTrue(s.hasQueuedThreads());
476 >            assertFalse(clone.hasQueuedThreads());
477 >            s.release();
478 >            awaitTermination(t);
479 >            assertFalse(s.hasQueuedThreads());
480 >            assertFalse(clone.hasQueuedThreads());
481 >        } catch (InterruptedException e) { threadUnexpectedException(e); }
482      }
483  
484      /**
485 <     * release(n) in one thread enables timed acquire(n) in another thread
485 >     * tryAcquire(n) succeeds when sufficient permits, else fails
486       */
487 <    public void testTimedAcquireReleaseNInSameThread_fair() {
488 <        Semaphore s = new Semaphore(1, true);
489 <        try {
490 <            s.release(1);
491 <            assertTrue(s.tryAcquire(1, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
492 <            s.release(2);
493 <            assertTrue(s.tryAcquire(2, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
494 <            s.release(3);
495 <            assertTrue(s.tryAcquire(3, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
496 <            s.release(4);
497 <            assertTrue(s.tryAcquire(4, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
498 <            s.release(5);
551 <            assertTrue(s.tryAcquire(5, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
552 <            assertEquals(1, s.availablePermits());
553 <        } catch( InterruptedException e){
554 <            unexpectedException();
555 <        }
487 >    public void testTryAcquireNInSameThread()      { testTryAcquireNInSameThread(false); }
488 >    public void testTryAcquireNInSameThread_fair() { testTryAcquireNInSameThread(true); }
489 >    public void testTryAcquireNInSameThread(boolean fair) {
490 >        Semaphore s = new Semaphore(2, fair);
491 >        assertEquals(2, s.availablePermits());
492 >        assertFalse(s.tryAcquire(3));
493 >        assertEquals(2, s.availablePermits());
494 >        assertTrue(s.tryAcquire(2));
495 >        assertEquals(0, s.availablePermits());
496 >        assertFalse(s.tryAcquire(1));
497 >        assertFalse(s.tryAcquire(2));
498 >        assertEquals(0, s.availablePermits());
499      }
500  
501      /**
502 <     * release in one thread enables timed acquire in another thread
502 >     * acquire succeeds if permits available
503       */
504 <    public void testTimedAcquireReleaseInSameThread_fair() {
505 <        Semaphore s = new Semaphore(1, true);
506 <        try {
507 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
508 <            s.release();
509 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
510 <            s.release();
511 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
512 <            s.release();
513 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
514 <            s.release();
515 <            assertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
516 <            s.release();
504 >    public void testReleaseAcquireSameThread_acquire()       { testReleaseAcquireSameThread(false, AcquireMethod.acquire); }
505 >    public void testReleaseAcquireSameThread_acquire_fair()  { testReleaseAcquireSameThread(true, AcquireMethod.acquire); }
506 >    public void testReleaseAcquireSameThread_acquireN()      { testReleaseAcquireSameThread(false, AcquireMethod.acquireN); }
507 >    public void testReleaseAcquireSameThread_acquireN_fair() { testReleaseAcquireSameThread(true, AcquireMethod.acquireN); }
508 >    public void testReleaseAcquireSameThread_acquireUninterruptibly()       { testReleaseAcquireSameThread(false, AcquireMethod.acquireUninterruptibly); }
509 >    public void testReleaseAcquireSameThread_acquireUninterruptibly_fair()  { testReleaseAcquireSameThread(true, AcquireMethod.acquireUninterruptibly); }
510 >    public void testReleaseAcquireSameThread_acquireUninterruptiblyN()      { testReleaseAcquireSameThread(false, AcquireMethod.acquireUninterruptibly); }
511 >    public void testReleaseAcquireSameThread_acquireUninterruptiblyN_fair() { testReleaseAcquireSameThread(true, AcquireMethod.acquireUninterruptibly); }
512 >    public void testReleaseAcquireSameThread_tryAcquire()       { testReleaseAcquireSameThread(false, AcquireMethod.tryAcquire); }
513 >    public void testReleaseAcquireSameThread_tryAcquire_fair()  { testReleaseAcquireSameThread(true, AcquireMethod.tryAcquire); }
514 >    public void testReleaseAcquireSameThread_tryAcquireN()      { testReleaseAcquireSameThread(false, AcquireMethod.tryAcquireN); }
515 >    public void testReleaseAcquireSameThread_tryAcquireN_fair() { testReleaseAcquireSameThread(true, AcquireMethod.tryAcquireN); }
516 >    public void testReleaseAcquireSameThread_tryAcquireTimed()       { testReleaseAcquireSameThread(false, AcquireMethod.tryAcquireTimed); }
517 >    public void testReleaseAcquireSameThread_tryAcquireTimed_fair()  { testReleaseAcquireSameThread(true, AcquireMethod.tryAcquireTimed); }
518 >    public void testReleaseAcquireSameThread_tryAcquireTimedN()      { testReleaseAcquireSameThread(false, AcquireMethod.tryAcquireTimedN); }
519 >    public void testReleaseAcquireSameThread_tryAcquireTimedN_fair() { testReleaseAcquireSameThread(true, AcquireMethod.tryAcquireTimedN); }
520 >    public void testReleaseAcquireSameThread(boolean fair,
521 >                                             final AcquireMethod acquirer) {
522 >        Semaphore s = new Semaphore(1, fair);
523 >        for (int i = 1; i < 6; i++) {
524 >            s.release(i);
525 >            assertEquals(1 + i, s.availablePermits());
526 >            try {
527 >                acquirer.acquire(s, i);
528 >            } catch (InterruptedException e) { threadUnexpectedException(e); }
529              assertEquals(1, s.availablePermits());
575        } catch( InterruptedException e){
576            unexpectedException();
530          }
531      }
532  
533      /**
534 <     * A release in one thread enables an acquire in another thread
582 <     */
583 <    public void testAcquireReleaseInDifferentThreads_fair() {
584 <        final Semaphore s = new Semaphore(0, true);
585 <        Thread t = new Thread(new Runnable() {
586 <                public void run() {
587 <                    try {
588 <                        s.acquire();
589 <                        s.acquire();
590 <                        s.acquire();
591 <                        s.acquire();
592 <                    } catch(InterruptedException ie){
593 <                        threadUnexpectedException();
594 <                    }
595 <                }
596 <            });
597 <        try {
598 <            t.start();
599 <            Thread.sleep(SHORT_DELAY_MS);
600 <            s.release();
601 <            s.release();
602 <            s.release();
603 <            s.release();
604 <            s.release();
605 <            s.release();
606 <            t.join();
607 <            assertEquals(2, s.availablePermits());
608 <        } catch( InterruptedException e){
609 <            unexpectedException();
610 <        }
611 <    }
612 <
613 <    /**
614 <     * release(n) in one thread enables acquire(n) in another thread
615 <     */
616 <    public void testAcquireReleaseNInDifferentThreads_fair() {
617 <        final Semaphore s = new Semaphore(0, true);
618 <        Thread t = new Thread(new Runnable() {
619 <                public void run() {
620 <                    try {
621 <                        s.acquire();
622 <                        s.release(2);
623 <                        s.acquire();
624 <                    } catch(InterruptedException ie){
625 <                        threadUnexpectedException();
626 <                    }
627 <                }
628 <            });
629 <        try {
630 <            t.start();
631 <            Thread.sleep(SHORT_DELAY_MS);
632 <            s.release(2);
633 <            s.acquire(2);
634 <            s.release(1);
635 <            t.join();
636 <        } catch( InterruptedException e){
637 <            unexpectedException();
638 <        }
639 <    }
640 <
641 <    /**
642 <     * release(n) in one thread enables acquire(n) in another thread
643 <     */
644 <    public void testAcquireReleaseNInDifferentThreads_fair2() {
645 <        final Semaphore s = new Semaphore(0, true);
646 <        Thread t = new Thread(new Runnable() {
647 <                public void run() {
648 <                    try {
649 <                        s.acquire(2);
650 <                        s.acquire(2);
651 <                        s.release(4);
652 <                    } catch(InterruptedException ie){
653 <                        threadUnexpectedException();
654 <                    }
655 <                }
656 <            });
657 <        try {
658 <            t.start();
659 <            Thread.sleep(SHORT_DELAY_MS);
660 <            s.release(6);
661 <            s.acquire(2);
662 <            s.acquire(2);
663 <            s.release(2);
664 <            t.join();
665 <        } catch( InterruptedException e){
666 <            unexpectedException();
667 <        }
668 <    }
669 <
670 <
671 <
672 <
673 <
674 <    /**
675 <     * release in one thread enables timed acquire in another thread
534 >     * release in one thread enables acquire in another thread
535       */
536 <    public void testTimedAcquireReleaseInDifferentThreads_fair() {
537 <        final Semaphore s = new Semaphore(1, true);
538 <        Thread t = new Thread(new Runnable() {
539 <                public void run() {
540 <                    try {
541 <                        threadAssertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
542 <                        threadAssertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
543 <                        threadAssertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
544 <                        threadAssertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
545 <                        threadAssertTrue(s.tryAcquire(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
546 <
547 <                    } catch(InterruptedException ie){
548 <                        threadUnexpectedException();
549 <                    }
550 <                }
551 <            });
552 <        t.start();
553 <        try {
554 <            s.release();
555 <            s.release();
556 <            s.release();
557 <            s.release();
558 <            s.release();
559 <            t.join();
560 <        } catch( InterruptedException e){
561 <            unexpectedException();
562 <        }
563 <    }
564 <
565 <    /**
566 <     * release(n) in one thread enables timed acquire(n) in another thread
567 <     */
568 <    public void testTimedAcquireReleaseNInDifferentThreads_fair() {
569 <        final Semaphore s = new Semaphore(2, true);
570 <        Thread t = new Thread(new Runnable() {
712 <                public void run() {
713 <                    try {
714 <                        threadAssertTrue(s.tryAcquire(2, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
715 <                        s.release(2);
716 <                        threadAssertTrue(s.tryAcquire(2, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
717 <                        s.release(2);
718 <                    } catch(InterruptedException ie){
719 <                        threadUnexpectedException();
720 <                    }
721 <                }
722 <            });
723 <        t.start();
724 <        try {
725 <            assertTrue(s.tryAcquire(2, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
726 <            s.release(2);
727 <            assertTrue(s.tryAcquire(2, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
728 <            s.release(2);
729 <            t.join();
730 <        } catch( InterruptedException e){
731 <            unexpectedException();
732 <        }
733 <    }
734 <
735 <    /**
736 <     * A waiting acquire blocks interruptibly
737 <     */
738 <    public void testAcquire_InterruptedException_fair() {
739 <        final Semaphore s = new Semaphore(0, true);
740 <        Thread t = new Thread(new Runnable() {
741 <                public void run() {
742 <                    try {
743 <                        s.acquire();
744 <                        threadShouldThrow();
745 <                    } catch(InterruptedException success){}
746 <                }
747 <            });
748 <        t.start();
749 <        try {
750 <            Thread.sleep(SHORT_DELAY_MS);
751 <            t.interrupt();
752 <            t.join();
753 <        } catch(InterruptedException e){
754 <            unexpectedException();
755 <        }
756 <    }
757 <
758 <    /**
759 <     * A waiting acquire(n) blocks interruptibly
760 <     */
761 <    public void testAcquireN_InterruptedException_fair() {
762 <        final Semaphore s = new Semaphore(2, true);
763 <        Thread t = new Thread(new Runnable() {
764 <                public void run() {
765 <                    try {
766 <                        s.acquire(3);
767 <                        threadShouldThrow();
768 <                    } catch(InterruptedException success){}
769 <                }
770 <            });
771 <        t.start();
772 <        try {
773 <            Thread.sleep(SHORT_DELAY_MS);
774 <            t.interrupt();
775 <            t.join();
776 <        } catch(InterruptedException e){
777 <            unexpectedException();
778 <        }
779 <    }
780 <    
781 <    /**
782 <     *  A waiting tryAcquire blocks interruptibly
783 <     */
784 <    public void testTryAcquire_InterruptedException_fair() {
785 <        final Semaphore s = new Semaphore(0, true);
786 <        Thread t = new Thread(new Runnable() {
787 <                public void run() {
788 <                    try {
789 <                        s.tryAcquire(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
790 <                        threadShouldThrow();
791 <                    } catch(InterruptedException success){
792 <                    }
793 <                }
794 <            });
795 <        t.start();
796 <        try {
797 <            Thread.sleep(SHORT_DELAY_MS);
798 <            t.interrupt();
799 <            t.join();
800 <        } catch(InterruptedException e){
801 <            unexpectedException();
802 <        }
803 <    }
804 <
805 <    /**
806 <     *  A waiting tryAcquire(n) blocks interruptibly
807 <     */
808 <    public void testTryAcquireN_InterruptedException_fair() {
809 <        final Semaphore s = new Semaphore(1, true);
810 <        Thread t = new Thread(new Runnable() {
811 <                public void run() {
812 <                    try {
813 <                        s.tryAcquire(4, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
814 <                        threadShouldThrow();
815 <                    } catch(InterruptedException success){
816 <                    }
817 <                }
818 <            });
819 <        t.start();
820 <        try {
821 <            Thread.sleep(SHORT_DELAY_MS);
822 <            t.interrupt();
823 <            t.join();
824 <        } catch(InterruptedException e){
825 <            unexpectedException();
536 >    public void testReleaseAcquireDifferentThreads_acquire()       { testReleaseAcquireDifferentThreads(false, AcquireMethod.acquire); }
537 >    public void testReleaseAcquireDifferentThreads_acquire_fair()  { testReleaseAcquireDifferentThreads(true, AcquireMethod.acquire); }
538 >    public void testReleaseAcquireDifferentThreads_acquireN()      { testReleaseAcquireDifferentThreads(false, AcquireMethod.acquireN); }
539 >    public void testReleaseAcquireDifferentThreads_acquireN_fair() { testReleaseAcquireDifferentThreads(true, AcquireMethod.acquireN); }
540 >    public void testReleaseAcquireDifferentThreads_acquireUninterruptibly()       { testReleaseAcquireDifferentThreads(false, AcquireMethod.acquireUninterruptibly); }
541 >    public void testReleaseAcquireDifferentThreads_acquireUninterruptibly_fair()  { testReleaseAcquireDifferentThreads(true, AcquireMethod.acquireUninterruptibly); }
542 >    public void testReleaseAcquireDifferentThreads_acquireUninterruptiblyN()      { testReleaseAcquireDifferentThreads(false, AcquireMethod.acquireUninterruptibly); }
543 >    public void testReleaseAcquireDifferentThreads_acquireUninterruptiblyN_fair() { testReleaseAcquireDifferentThreads(true, AcquireMethod.acquireUninterruptibly); }
544 >    public void testReleaseAcquireDifferentThreads_tryAcquireTimed()       { testReleaseAcquireDifferentThreads(false, AcquireMethod.tryAcquireTimed); }
545 >    public void testReleaseAcquireDifferentThreads_tryAcquireTimed_fair()  { testReleaseAcquireDifferentThreads(true, AcquireMethod.tryAcquireTimed); }
546 >    public void testReleaseAcquireDifferentThreads_tryAcquireTimedN()      { testReleaseAcquireDifferentThreads(false, AcquireMethod.tryAcquireTimedN); }
547 >    public void testReleaseAcquireDifferentThreads_tryAcquireTimedN_fair() { testReleaseAcquireDifferentThreads(true, AcquireMethod.tryAcquireTimedN); }
548 >    public void testReleaseAcquireDifferentThreads(boolean fair,
549 >                                                   final AcquireMethod acquirer) {
550 >        final Semaphore s = new Semaphore(0, fair);
551 >        final int rounds = 4;
552 >        long startTime = System.nanoTime();
553 >        Thread t = newStartedThread(new CheckedRunnable() {
554 >            public void realRun() throws InterruptedException {
555 >                for (int i = 0; i < rounds; i++) {
556 >                    assertFalse(s.hasQueuedThreads());
557 >                    if (i % 2 == 0)
558 >                        acquirer.acquire(s);
559 >                    else
560 >                        acquirer.acquire(s, 3);
561 >                }}});
562 >
563 >        for (int i = 0; i < rounds; i++) {
564 >            while (! (s.availablePermits() == 0 && s.hasQueuedThreads()))
565 >                Thread.yield();
566 >            assertTrue(t.isAlive());
567 >            if (i % 2 == 0)
568 >                s.release();
569 >            else
570 >                s.release(3);
571          }
572 +        awaitTermination(t);
573 +        assertEquals(0, s.availablePermits());
574 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
575      }
576  
577      /**
578 <     * getQueueLength reports number of waiting threads
578 >     * fair locks are strictly FIFO
579       */
580 <    public void testGetQueueLength_fair() {
581 <        final Semaphore lock = new Semaphore(1, true);
582 <        Thread t1 = new Thread(new InterruptedLockRunnable(lock));
583 <        Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
584 <        try {
585 <            assertEquals(0, lock.getQueueLength());
586 <            lock.acquireUninterruptibly();
587 <            t1.start();
588 <            Thread.sleep(SHORT_DELAY_MS);
589 <            assertEquals(1, lock.getQueueLength());
590 <            t2.start();
591 <            Thread.sleep(SHORT_DELAY_MS);
592 <            assertEquals(2, lock.getQueueLength());
593 <            t1.interrupt();
594 <            Thread.sleep(SHORT_DELAY_MS);
595 <            assertEquals(1, lock.getQueueLength());
596 <            lock.release();
597 <            Thread.sleep(SHORT_DELAY_MS);
598 <            assertEquals(0, lock.getQueueLength());
599 <            t1.join();
600 <            t2.join();
601 <        } catch(Exception e){
602 <            unexpectedException();
603 <        }
604 <    }
605 <
606 <
607 <    /**
608 <     * a deserialized serialized semaphore has same number of permits
609 <     */
610 <    public void testSerialization_fair() {
611 <        Semaphore l = new Semaphore(3, true);
612 <
613 <        try {
614 <            l.acquire();
615 <            l.release();
616 <            ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
617 <            ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
618 <            out.writeObject(l);
619 <            out.close();
620 <
621 <            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
622 <            ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
623 <            Semaphore r = (Semaphore) in.readObject();
624 <            assertEquals(3, r.availablePermits());
625 <            assertTrue(r.isFair());
626 <            r.acquire();
627 <            r.release();
628 <        } catch(Exception e){
629 <            unexpectedException();
630 <        }
580 >    public void testFairLocksFifo() {
581 >        final PublicSemaphore s = new PublicSemaphore(1, true);
582 >        final CountDownLatch pleaseRelease = new CountDownLatch(1);
583 >        Thread t1 = newStartedThread(new CheckedRunnable() {
584 >            public void realRun() throws InterruptedException {
585 >                // Will block; permits are available, but not three
586 >                s.acquire(3);
587 >            }});
588 >
589 >        waitForQueuedThreads(s);
590 >
591 >        Thread t2 = newStartedThread(new CheckedRunnable() {
592 >            public void realRun() throws InterruptedException {
593 >                // Will fail, even though 1 permit is available
594 >                assertFalse(s.tryAcquire(0L, MILLISECONDS));
595 >                assertFalse(s.tryAcquire(1, 0L, MILLISECONDS));
596 >
597 >                // untimed tryAcquire will barge and succeed
598 >                assertTrue(s.tryAcquire());
599 >                s.release(2);
600 >                assertTrue(s.tryAcquire(2));
601 >                s.release();
602 >
603 >                pleaseRelease.countDown();
604 >                // Will queue up behind t1, even though 1 permit is available
605 >                s.acquire();
606 >            }});
607 >
608 >        await(pleaseRelease);
609 >        waitForQueuedThread(s, t2);
610 >        s.release(2);
611 >        awaitTermination(t1);
612 >        assertTrue(t2.isAlive());
613 >        s.release();
614 >        awaitTermination(t2);
615 >   }
616 >
617 >    /**
618 >     * toString indicates current number of permits
619 >     */
620 >    public void testToString()      { testToString(false); }
621 >    public void testToString_fair() { testToString(true); }
622 >    public void testToString(boolean fair) {
623 >        PublicSemaphore s = new PublicSemaphore(0, fair);
624 >        assertTrue(s.toString().contains("Permits = 0"));
625 >        s.release();
626 >        assertTrue(s.toString().contains("Permits = 1"));
627 >        s.release(2);
628 >        assertTrue(s.toString().contains("Permits = 3"));
629 >        s.reducePermits(5);
630 >        assertTrue(s.toString().contains("Permits = -2"));
631      }
632  
885
633   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines