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 * Release lock command for execution on group member.
027 * @author Paul Ferraro
028 */
029public class MemberReleaseLockCommand implements Command<Void, LockCommandContext>
030{
031        private static final long serialVersionUID = -4088487420468046409L;
032
033        private final RemoteLockDescriptor descriptor;
034        
035        public MemberReleaseLockCommand(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 Void execute(LockCommandContext context)
046        {
047                Map<LockDescriptor, Lock> locks = context.getRemoteLocks(this.descriptor);
048                
049                if (locks != null)
050                {
051                        Lock lock = null;
052                        
053                        synchronized (locks)
054                        {
055                                lock = locks.remove(this.descriptor);
056                        }
057                        
058                        if (lock != null)
059                        {
060                                lock.unlock();
061                        }
062                }
063
064                return null;
065        }
066
067        /**
068         * {@inheritDoc}
069         * @see java.lang.Object#toString()
070         */
071        @Override
072        public String toString()
073        {
074                return String.format("%s(%s)", this.getClass().getSimpleName(), this.descriptor);
075        }
076}