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.invocation;
019
020import java.util.List;
021import java.util.SortedMap;
022import java.util.concurrent.locks.Lock;
023
024import net.sf.hajdbc.Database;
025import net.sf.hajdbc.sql.ProxyFactory;
026
027/**
028 * An invocation strategy decorator that acquires a list of locks before invocation, and releases them afterward.
029 * @author Paul Ferraro
030 */
031public class LockingInvocationStrategy implements InvocationStrategy
032{
033        private InvocationStrategy strategy;
034        private List<Lock> lockList;
035        
036        /**
037         * @param strategy
038         * @param lockList
039         */
040        public LockingInvocationStrategy(InvocationStrategy strategy, List<Lock> lockList)
041        {
042                this.strategy = strategy;
043                this.lockList = lockList;
044        }
045
046        /**
047         * {@inheritDoc}
048         */
049        @Override
050        public <Z, D extends Database<Z>, T, R, E extends Exception> SortedMap<D, R> invoke(ProxyFactory<Z, D, T, E> proxy, Invoker<Z, D, T, R, E> invoker) throws E
051        {
052                for (Lock lock: this.lockList)
053                {
054                        lock.lock();
055                }
056                
057                try
058                {
059                        return this.strategy.invoke(proxy, invoker);
060                }
061                finally
062                {
063                        for (Lock lock: this.lockList)
064                        {
065                                lock.unlock();
066                        }
067                }
068        }
069}