11 |
|
import java.util.Collection; |
12 |
|
import java.util.concurrent.CountDownLatch; |
13 |
|
import java.util.concurrent.Semaphore; |
14 |
+ |
import java.util.concurrent.ThreadLocalRandom; |
15 |
|
|
16 |
|
import junit.framework.AssertionFailedError; |
17 |
|
import junit.framework.Test; |
194 |
|
/** |
195 |
|
* timed tryAcquire times out |
196 |
|
*/ |
197 |
< |
public void testTryAcquire_timeout() { testTryAcquire_timeout(false); } |
198 |
< |
public void testTryAcquire_timeout_fair() { testTryAcquire_timeout(true); } |
199 |
< |
public void testTryAcquire_timeout(boolean fair) { |
200 |
< |
Semaphore s = new Semaphore(0, fair); |
201 |
< |
long startTime = System.nanoTime(); |
197 |
> |
public void testTryAcquire_timeout() { |
198 |
> |
final ThreadLocalRandom rnd = ThreadLocalRandom.current(); |
199 |
> |
final boolean fair = rnd.nextBoolean(); |
200 |
> |
final Semaphore s = new Semaphore(0, fair); |
201 |
> |
final long startTime = System.nanoTime(); |
202 |
|
try { assertFalse(s.tryAcquire(timeoutMillis(), MILLISECONDS)); } |
203 |
|
catch (InterruptedException e) { threadUnexpectedException(e); } |
204 |
|
assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); |
207 |
|
/** |
208 |
|
* timed tryAcquire(N) times out |
209 |
|
*/ |
210 |
< |
public void testTryAcquireN_timeout() { testTryAcquireN_timeout(false); } |
211 |
< |
public void testTryAcquireN_timeout_fair() { testTryAcquireN_timeout(true); } |
212 |
< |
public void testTryAcquireN_timeout(boolean fair) { |
213 |
< |
Semaphore s = new Semaphore(2, fair); |
214 |
< |
long startTime = System.nanoTime(); |
210 |
> |
public void testTryAcquireN_timeout() { |
211 |
> |
final ThreadLocalRandom rnd = ThreadLocalRandom.current(); |
212 |
> |
final boolean fair = rnd.nextBoolean(); |
213 |
> |
final Semaphore s = new Semaphore(2, fair); |
214 |
> |
final long startTime = System.nanoTime(); |
215 |
|
try { assertFalse(s.tryAcquire(3, timeoutMillis(), MILLISECONDS)); } |
216 |
|
catch (InterruptedException e) { threadUnexpectedException(e); } |
217 |
|
assertTrue(millisElapsedSince(startTime) >= timeoutMillis()); |