My favorites | Sign in
Project Home Downloads Wiki Issues Source
Checkout   Browse   Changes    
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
*
*/
package fr.xebia.concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

final public class CyclicLatch {
private final int initialcount;
private CountDownLatch latch;
private final ReentrantLock lock = new ReentrantLock();
private final long defaultTimeout;
private final TimeUnit defaultTimeUnit;

/**
* Create a new CyclicLatch with a 15 secondes Timeout;
*
* @param initialcount
*/
public CyclicLatch(int initialcount) {
this(initialcount, 15, TimeUnit.SECONDS);
}

public CyclicLatch(int initialcount, long defaultTimeout,
TimeUnit defaultTimeUnit) {
this.initialcount = initialcount;
this.defaultTimeout = defaultTimeout;
this.defaultTimeUnit = defaultTimeUnit;
this.latch = new CountDownLatch(initialcount);
}

public void countDown() {
try {
lock.lock();
latch.countDown();
} finally {
lock.unlock();
}
}

/**
* Await the opening of the Latch
*
* @return false if the opening has been done on Timeout, true if the
* opening has been done on overflow.
* @throws InterruptedException
*/
public boolean await() throws InterruptedException {
return await(this.defaultTimeout, defaultTimeUnit);
}

/**
* Await the opening of the Latch with a dedicated timeout (value + unit)
*
* @param timeout
* @param unit
* @return false if the opening has been done on Timeout, true if the
* opening has been done on overflow.
*
* @throws InterruptedException
*/
public boolean await(long timeout, TimeUnit unit)
throws InterruptedException {

log("Waiting for latch of "+this.initialcount+" & " + timeout + " seconds timeout");
boolean result = latch.await(timeout, unit);
/* Reset Latch, on timeout & on overflow */
try {
lock.lock();
log("Reset Latch...." + latch);
latch = new CountDownLatch(initialcount);
} finally {
lock.unlock();
}
return result;

}

public String toString() {
return this.latch.toString() + "/[Initial = " + this.initialcount + "]";
}

void log(Object o) {
System.out.println(Thread.currentThread().getName() + " " + o);
}

}

Change log

r141 by bmoussaud on Sep 15, 2008   Diff
Import concurrent.cycliclatch
Go to: 
Sign in to write a code review

Older revisions

All revisions of this file

File info

Size: 2274 bytes, 89 lines
Powered by Google Project Hosting