View Javadoc
1 /* 2 * Copyright (C) The Apache Software Foundation. All rights reserved. 3 * 4 * This software is published under the terms of the Apache Software License 5 * version 1.1, a copy of which has been included with this distribution in 6 * the LICENSE file. 7 */ 8 package org.apache.james.util; 9 10 import java.util.Hashtable; 11 12 /*** 13 * Provides Lock functionality 14 * 15 * @author Federico Barbieri <fede@apache.org> 16 */ 17 public class Lock { 18 /*** 19 * An internal hash table of keys to locks 20 */ 21 private Hashtable locks = new Hashtable(); 22 23 /*** 24 * Check to see if the object is locked 25 * 26 * @param key the Object on which to check the lock 27 * @return true if the object is locked, false otherwise 28 */ 29 public boolean isLocked(final Object key) { 30 return (locks.get(key) != null); 31 } 32 33 /*** 34 * Check to see if we can lock on a given object. 35 * 36 * @param key the Object on which to lock 37 * @return true if the calling thread can lock, false otherwise 38 */ 39 public boolean canI(final Object key) { 40 Object o = locks.get( key ); 41 42 if (null == o || o == this.getCallerId()) { 43 return true; 44 } 45 46 return false; 47 } 48 49 /*** 50 * Lock on a given object. 51 * 52 * @param key the Object on which to lock 53 * @return true if the locking was successful, false otherwise 54 */ 55 public boolean lock(final Object key) { 56 Object theLock; 57 58 synchronized(this) { 59 theLock = locks.get(key); 60 61 if (null == theLock) { 62 locks.put(key, getCallerId()); 63 return true; 64 } else if (getCallerId() == theLock) { 65 return true; 66 } else { 67 return false; 68 } 69 } 70 } 71 72 /*** 73 * Release the lock on a given object. 74 * 75 * @param key the Object on which the lock is held 76 * @return true if the unlocking was successful, false otherwise 77 */ 78 public boolean unlock(final Object key) { 79 Object theLock; 80 synchronized (this) { 81 theLock = locks.get(key); 82 83 if (null == theLock) { 84 return true; 85 } else if (getCallerId() == theLock) { 86 locks.remove(key); 87 return true; 88 } else { 89 return false; 90 } 91 } 92 } 93 94 /*** 95 * Private helper method to abstract away caller ID. 96 * 97 * @return the id of the caller (i.e. the Thread reference) 98 */ 99 private Object getCallerId() { 100 return Thread.currentThread(); 101 } 102 }

This page was automatically generated by Maven