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