All Downloads are FREE. Search and download functionalities are using the official Maven repository.

jodd.util.Mutex Maven / Gradle / Ivy

There is a newer version: 3.4.1
Show newest version
// Copyright (c) 2003-2010, Jodd Team (jodd.org). All Rights Reserved.

package jodd.util;

/**
 * Provides simple mutual exclusion.
 * 

* Interesting, the previous implementation based on Leslie Lamport's * "Fast Mutal Exclusion" algorithm was not working, probably due wrong * implementation. *

* 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 returns. */ 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 false, */ 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(); } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy