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.distributed; 019 020import java.util.Map; 021import java.util.concurrent.locks.Lock; 022 023import net.sf.hajdbc.distributed.Command; 024 025/** 026 * @author Paul Ferraro 027 * 028 */ 029public class MemberAcquireLockCommand implements Command<Boolean, LockCommandContext> 030{ 031 private static final long serialVersionUID = 673191217118566395L; 032 033 private final RemoteLockDescriptor descriptor; 034 035 public MemberAcquireLockCommand(RemoteLockDescriptor descriptor) 036 { 037 this.descriptor = descriptor; 038 } 039 040 /** 041 * {@inheritDoc} 042 * @see net.sf.hajdbc.distributed.Command#execute(java.lang.Object) 043 */ 044 @Override 045 public Boolean execute(LockCommandContext context) 046 { 047 Lock lock = context.getLock(this.descriptor); 048 049 boolean locked = lock.tryLock(); 050 051 if (locked) 052 { 053 Map<LockDescriptor, Lock> lockMap = context.getRemoteLocks(this.descriptor); 054 055 synchronized (lockMap) 056 { 057 lockMap.put(this.descriptor, lock); 058 } 059 } 060 061 return locked; 062 } 063 064 /** 065 * {@inheritDoc} 066 * @see java.lang.Object#toString() 067 */ 068 @Override 069 public String toString() 070 { 071 return String.format("%s(%s)", this.getClass().getSimpleName(), this.descriptor); 072 } 073}