File D:\maven-qcr-plugin-testsunitaires\qcr4java\jenkins-master\target\site\qc\core\src\main\java\hudson\util\OneShotEvent.java.html

1 /*
2 * The MIT License
3 *
4 * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24 package hudson.util;
25
26 /**
27 * Concurrency primitive.
28 *
29 * <p>
30 * A {@link OneShotEvent} is like a pandora's box.
31 * It starts with the closed (non-signaled) state.
32 * Multiple threads can wait for the event to become the signaled state.
33 *
34 * <p>
35 * Once the event becomes signaled, or the pandora's box is opened,
36 * every thread gets through freely, and there's no way to turn it back off.
37 *
38 * @author Kohsuke Kawaguchi
39 */
40 public final class OneShotEvent {
41 private boolean signaled;
42 private final Object lock;
43
44 public OneShotEvent() {
45 this.lock = this;
46 }
47
48 public OneShotEvent(Object lock) {
49 this.lock = lock;
50 }
51
52 /**
53 * Non-blocking method that signals this event.
54 */
55 public void signal() {
56 synchronized (lock) {
57 if(signaled) return;
58 this.signaled = true;
59 lock.notifyAll();
60 }
61 }
62
63 /**
64 * Blocks until the event becomes the signaled state.
65 *
66 * <p>
67 * This method blocks infinitely until a value is offered.
68 */
69 public void block() throws InterruptedException {
70 synchronized (lock) {
71 while(!signaled)
72 lock.wait();
73 }
74 }
75
76 /**
77 * Blocks until the event becomes the signaled state.
78 *
79 * <p>
80 * If the specified amount of time elapses,
81 * this method returns null even if the value isn't offered.
82 */
83 public void block(long timeout) throws InterruptedException {
84 synchronized (lock) {
85 if(!signaled)
86 lock.wait(timeout);
87 }
88 }
89
90 /**
91 * Returns true if a value is offered.
92 */
93 public boolean isSignaled() {
94 synchronized (lock) {
95 return signaled;
96 }
97 }
98 }
99