summaryrefslogtreecommitdiff
path: root/java/src/Mutex.java
blob: ba1e13882aefa11118758817e28b9f8b862306c2 (plain)
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
90
91
92
/*************************************************
 *
 * = PACKAGE
 *    ACE.Concurrency
 *
 * = FILENAME
 *    Mutex.java
 *
 *@author Prashant Jain
 *
 *************************************************/
package ACE.Concurrency;

import java.util.*;
import ACE.ASX.*;

class TimedWaitMAdapter extends TimedWait
{
  TimedWaitMAdapter (Object obj)
  {
    super (obj);
  }

  // Check to see if the lock is currently held or not.
  public boolean condition ()
  {
    return !this.inUse_;
  }

  // Acquire/Release the lock
  public void inUse (boolean c)
  {
    this.inUse_ = c;
  }

  private boolean inUse_ = false;
  // The actual lock
}


/**
 * <hr>
 * <h2>SYNOPSIS</h2>
 *<blockquote>
 *     Value added abstraction for mutex variable creation.
 *</blockquote>
 *
 * <h2>DESCRIPTION</h2>
 *<blockquote>
 *     A timed mutex, <em>i.e.</em> a mutex whose operations do not
 * block forever and can <q>time out</q>.
 *</blockquote>
 */
public class Mutex
{
  /**
   * Acquire the mutex. Note that this will block.
   *@exception InterruptedException exception during wait
   */
  public synchronized void acquire () throws InterruptedException
    {
      this.monitor_.timedWait ();
      this.monitor_.inUse (true);
    }

  /**
   * Acquire the mutex. Note that the call will return if <timeout>
   * amount of time expires.
   *@param tv amount of time (TimeValue) to wait before returning
   * (unless operation completes before)
   *@exception TimeoutException wait timed out exception
   *@exception InterruptedException exception during wait
   */
  public synchronized void acquire (TimeValue tv) throws
  TimeoutException, InterruptedException 
    {
      this.monitor_.timedWait (tv);
      this.monitor_.inUse (true);
    }

  /**
   * Release the mutex.
   */
  public synchronized void release ()
    {
      this.monitor_.inUse (false);
      this.monitor_.signal ();
    }

  private TimedWaitMAdapter monitor_ = new TimedWaitMAdapter (this);
  // The monitor (adapter) to wait on
}