Mutex.java :  » Development » jodd » jodd » util » Java Open Source

Java Open Source » Development » jodd 
jodd » jodd » util » Mutex.java
// Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.

package jodd.util;

/**
 * Provides simple mutual exclusion.
 * <p>
 * Interesting, the previous implementation based on Leslie Lamport's
 * "Fast Mutal Exclusion" algorithm was not working, proabably due wrong
 * implementation.
 * <p>
 * Object (i.e. resource) that uses Mutex must be accessed only between
 * {@link #lock()} and {@link #unlock()}.
 */
public class Mutex {

  private Thread owner;

  /**
   * Blocks execution and acquires a lock. If already inside of critical block,
   * it simply returs.
   */
  public synchronized void lock() {
    Thread currentThread = Thread.currentThread();
    if (owner == currentThread) {
      return;
    }
    while (owner != null) {
      try {
        wait();
      } catch (InterruptedException iex) {
        notify();
      }
    }
    owner = currentThread;
  }

  /**
   * Acquires a lock. If lock already acquired, returns <code>false</code>,
   */
  public synchronized boolean tryLock() {
    Thread currentThread = Thread.currentThread();
    if (owner == currentThread) {
      return true;
    }
    if (owner != null) {
      return false;
    }
    owner = currentThread;
    return true;
  }

  /**
   * Releases a lock.
   */
  public synchronized void unlock() {
    owner = null;
    notify();
  }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.