001/* 002 * HA-JDBC: High-Availability JDBC 003 * Copyright (c) 2004-2007 Paul Ferraro 004 * 005 * This library is free software; you can redistribute it and/or modify it 006 * under the terms of the GNU Lesser General Public License as published by the 007 * Free Software Foundation; either version 2.1 of the License, or (at your 008 * option) any later version. 009 * 010 * This library is distributed in the hope that it will be useful, but WITHOUT 011 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 012 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License 013 * for more details. 014 * 015 * You should have received a copy of the GNU Lesser General Public License 016 * along with this library; if not, write to the Free Software Foundation, 017 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 018 * 019 * Contact: ferraro@users.sourceforge.net 020 */ 021package net.sf.hajdbc.util.concurrent; 022 023import java.util.concurrent.Semaphore; 024import java.util.concurrent.TimeUnit; 025import java.util.concurrent.locks.Condition; 026import java.util.concurrent.locks.Lock; 027 028/** 029 * An implementation of {@link java.util.concurrent.locks.Lock} using a binary semaphore. 030 * Unlike the {@link java.util.concurrent.locks.ReentrantLock} this lock can be locked and unlocked by different threads. 031 * Conditions are not supported. 032 * 033 * @author Paul Ferraro 034 */ 035public class SemaphoreLock implements Lock 036{ 037 private final Semaphore semaphore; 038 039 public SemaphoreLock(boolean fair) 040 { 041 this(new Semaphore(1, fair)); 042 } 043 044 SemaphoreLock(Semaphore semaphore) 045 { 046 this.semaphore = semaphore; 047 } 048 049 /** 050 * @see java.util.concurrent.locks.Lock#lock() 051 */ 052 @Override 053 public void lock() 054 { 055 this.semaphore.acquireUninterruptibly(); 056 } 057 058 /** 059 * @see java.util.concurrent.locks.Lock#lockInterruptibly() 060 */ 061 @Override 062 public void lockInterruptibly() throws InterruptedException 063 { 064 this.semaphore.acquire(); 065 } 066 067 /** 068 * @see java.util.concurrent.locks.Lock#newCondition() 069 */ 070 @Override 071 public Condition newCondition() 072 { 073 throw new UnsupportedOperationException(); 074 } 075 076 /** 077 * @see java.util.concurrent.locks.Lock#tryLock() 078 */ 079 @Override 080 public boolean tryLock() 081 { 082 return this.semaphore.tryAcquire(); 083 } 084 085 /** 086 * @see java.util.concurrent.locks.Lock#tryLock(long, java.util.concurrent.TimeUnit) 087 */ 088 @Override 089 public boolean tryLock(long time, TimeUnit unit) throws InterruptedException 090 { 091 return this.semaphore.tryAcquire(time, unit); 092 } 093 094 /** 095 * @see java.util.concurrent.locks.Lock#unlock() 096 */ 097 @Override 098 public void unlock() 099 { 100 this.semaphore.release(); 101 } 102}