KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > swt > internal > Lock


1 /*******************************************************************************
2  * Copyright (c) 2000, 2005 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.swt.internal;
12
13 /**
14  * Instance of this represent a recursive monitor.
15  */

16 public class Lock {
17     int count, waitCount;
18     Thread JavaDoc owner;
19
20 /**
21  * Locks the monitor and returns the lock count. If
22  * the lock is owned by another thread, wait until
23  * the lock is released.
24  *
25  * @return the lock count
26  */

27 public int lock() {
28     synchronized (this) {
29         Thread JavaDoc current = Thread.currentThread();
30         if (owner != current) {
31             waitCount++;
32             while (count > 0) {
33                 try {
34                     wait();
35                 } catch (InterruptedException JavaDoc e) {
36                     /* Wait forever, just like synchronized blocks */
37                 }
38             }
39             --waitCount;
40             owner = current;
41         }
42         return ++count;
43     }
44 }
45
46 /**
47  * Unlocks the monitor. If the current thread is not
48  * the monitor owner, do nothing.
49  */

50 public void unlock() {
51     synchronized (this) {
52         Thread JavaDoc current = Thread.currentThread();
53         if (owner == current) {
54             if (--count == 0) {
55                 owner = null;
56                 if (waitCount > 0) notifyAll();
57             }
58         }
59     }
60 }
61 }
62
Popular Tags