blob: 1f6dd4e30c8d63d236544ec38991d5800858db06 [file] [log] [blame]
J. Duke319a3b92007-12-01 00:00:00 +00001/*
2 * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
20 * CA 95054 USA or visit www.sun.com if you need additional information or
21 * have any questions.
22 */
23
24/*
25 *
26 * @summary Thiseclass is used to synchronize execution off two threads.
27 * @author Swamy Venkataramanappa
28 */
29
30import java.util.concurrent.Semaphore;
31
32public class ThreadExecutionSynchronizer {
33
34 private boolean waiting;
35 private Semaphore semaphore;
36
37 public ThreadExecutionSynchronizer() {
38 semaphore = new Semaphore(1);
39 waiting = false;
40 }
41
42 // Synchronizes two threads execution points.
43 // Basically any thread could get scheduled to run and
44 // it is not possible to know which thread reaches expected
45 // execution point. So whichever thread reaches a execution
46 // point first wait for the second thread. When the second thread
47 // reaches the expected execution point will wake up
48 // the thread which is waiting here.
49 void stopOrGo() {
50 semaphore.acquireUninterruptibly(); // Thread can get blocked.
51 if (!waiting) {
52 waiting = true;
53 // Wait for second thread to enter this method.
54 while(!semaphore.hasQueuedThreads()) {
55 try {
56 Thread.sleep(20);
57 } catch (InterruptedException xx) {}
58 }
59 semaphore.release();
60 } else {
61 waiting = false;
62 semaphore.release();
63 }
64 }
65
66 // Wrapper function just for code readability.
67 void waitForSignal() {
68 stopOrGo();
69 goSleep(50);
70 }
71
72 void signal() {
73 stopOrGo();
74 goSleep(50);
75 }
76
77 private static void goSleep(long ms) {
78 try {
79 Thread.sleep(ms);
80 } catch (InterruptedException e) {
81 e.printStackTrace();
82 System.out.println("Unexpected exception.");
83 }
84 }
85}