You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by oz...@apache.org on 2004/06/06 15:11:04 UTC

cvs commit: jakarta-commons-sandbox/transaction/src/test/org/apache/commons/transaction/memory PessimisticMapWrapperTest.java

ozeigermann    2004/06/06 06:11:04

  Modified:    transaction/src/java/org/apache/commons/transaction/memory
                        PessimisticMapWrapper.java
  Added:       transaction/src/java/org/apache/commons/transaction/memory
                        LockException.java
               transaction/src/test/org/apache/commons/transaction/memory
                        PessimisticMapWrapperTest.java
  Log:
  Added initial version of pessimistic (locking) wrapper + test
  
  Revision  Changes    Path
  1.4       +152 -8    jakarta-commons-sandbox/transaction/src/java/org/apache/commons/transaction/memory/PessimisticMapWrapper.java
  
  Index: PessimisticMapWrapper.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons-sandbox/transaction/src/java/org/apache/commons/transaction/memory/PessimisticMapWrapper.java,v
  retrieving revision 1.3
  retrieving revision 1.4
  diff -u -r1.3 -r1.4
  --- PessimisticMapWrapper.java	5 Jun 2004 16:50:00 -0000	1.3
  +++ PessimisticMapWrapper.java	6 Jun 2004 13:11:04 -0000	1.4
  @@ -23,7 +23,17 @@
   
   package org.apache.commons.transaction.memory;
   
  +import java.util.Collection;
  +import java.util.HashSet;
  +import java.util.Iterator;
   import java.util.Map;
  +import java.util.Set;
  +
  +import org.apache.commons.transaction.locking.GenericLock;
  +import org.apache.commons.transaction.locking.GenericLockManager;
  +import org.apache.commons.transaction.locking.LockManager;
  +import org.apache.commons.transaction.locking.MultiLevelLock;
  +import org.apache.commons.transaction.util.LoggerFacade;
   
   /**
    * Wrapper that adds transactional control to all kinds of maps that implement the {@link Map} interface. By using
  @@ -31,7 +41,7 @@
    * also has less possible concurrency and may even deadlock. A commit, however, will never fail.
    * <br>
    * Start a transaction by calling {@link #startTransaction()}. Then perform the normal actions on the map and
  - * finally either calls {@link #commitTransaction()} to make your changes permanent or {@link #rollbackTransaction()} to
  + * finally either call {@link #commitTransaction()} to make your changes permanent or {@link #rollbackTransaction()} to
    * undo them.
    * <br>
    * <em>Caution:</em> Do not modify values retrieved by {@link #get(Object)} as this will circumvent the transactional mechanism.
  @@ -46,14 +56,23 @@
    */
   public class PessimisticMapWrapper extends TransactionalMapWrapper {
   
  +    protected static final int READ = 1;
  +    protected static final int WRITE = 2;
  +
  +    protected static final String GLOBAL_LOCK_NAME = "GLOBAL";
  +
  +    protected LockManager lockManager;
  +    protected MultiLevelLock globalLock;
  +    protected long readTimeOut = 60000; /* FIXME: pass in ctor */
  +
       /**
        * Creates a new pessimistic transactional map wrapper. Temporary maps and sets to store transactional
        * data will be instances of {@link java.util.HashMap} and {@link java.util.HashSet}. 
        * 
        * @param wrapped map to be wrapped
        */
  -    public PessimisticMapWrapper(Map wrapped) {
  -        super(wrapped, new HashMapFactory(), new HashSetFactory());
  +    public PessimisticMapWrapper(Map wrapped, LoggerFacade logger) {
  +        this(wrapped, new HashMapFactory(), new HashSetFactory(), logger);
       }
   
       /**
  @@ -64,7 +83,132 @@
        * @param mapFactory factory for temporary maps
        * @param setFactory factory for temporary sets
        */
  -    public PessimisticMapWrapper(Map wrapped, MapFactory mapFactory, SetFactory setFactory) {
  +    public PessimisticMapWrapper(Map wrapped, MapFactory mapFactory, SetFactory setFactory, LoggerFacade logger) {
           super(wrapped, mapFactory, setFactory);
  +        lockManager = new GenericLockManager(WRITE, logger);
  +        globalLock = new GenericLock(GLOBAL_LOCK_NAME, WRITE, logger);
  +    }
  +
  +    public void startTransaction() {
  +        if (getActiveTx() != null) {
  +            throw new IllegalStateException(
  +                "Active thread " + Thread.currentThread() + " already associated with a transaction!");
  +        }
  +        LockingTxContext context = new LockingTxContext();
  +        setActiveTx(context);
  +    }
  +
  +    public Collection values() {
  +        assureGlobalLock(READ);
  +        return super.values();
  +    }
  +
  +    public Set entrySet() {
  +        assureGlobalLock(READ);
  +        return super.entrySet();
  +    }
  +
  +    public Set keySet() {
  +        assureGlobalLock(READ);
  +        return super.keySet();
  +    }
  +
  +    public Object remove(Object key) {
  +        // assure we get a write lock before super can get a read lock to avoid lots
  +        // of deadlocks
  +        assureWriteLock(key);
  +        return super.remove(key);
  +    }
  +
  +    public Object put(Object key, Object value) {
  +        // assure we get a write lock before super can get a read lock to avoid lots
  +        // of deadlocks
  +        assureWriteLock(key);
  +        return super.put(key, value);
       }
  +
  +    protected void assureWriteLock(Object key) {
  +        LockingTxContext txContext = (LockingTxContext) getActiveTx();
  +        if (txContext != null) {
  +            txContext.lock(lockManager.atomicGetOrCreateLock(key), WRITE);
  +            txContext.lock(globalLock, READ); // XXX fake intention lock (prohibits global WRITE)
  +        }
  +    }
  +    
  +    protected void assureGlobalLock(int level) {
  +        LockingTxContext txContext = (LockingTxContext) getActiveTx();
  +        if (txContext != null) {
  +            txContext.lock(globalLock, level); // XXX fake intention lock (prohibits global WRITE)
  +        }
  +    }
  +    
  +    public class LockingTxContext extends TxContext {
  +        protected Set locks;
  +
  +        protected LockingTxContext() {
  +            super();
  +            locks = new HashSet();
  +        }
  +
  +        protected Set keys() {
  +            lock(globalLock, READ);
  +            return super.keys();
  +        }
  +
  +        protected Object get(Object key) {
  +            lock(lockManager.atomicGetOrCreateLock(key), READ);
  +            lock(globalLock, READ); // XXX fake intention lock (prohibits global WRITE)
  +            return super.get(key);
  +        }
  +
  +        protected void put(Object key, Object value) {
  +            lock(lockManager.atomicGetOrCreateLock(key), WRITE);
  +            lock(globalLock, READ); // XXX fake intention lock (prohibits global WRITE)
  +            super.put(key, value);
  +        }
  +
  +        protected void remove(Object key) {
  +            lock(lockManager.atomicGetOrCreateLock(key), WRITE);
  +            lock(globalLock, READ); // XXX fake intention lock (prohibits global WRITE)
  +            super.remove(key);
  +        }
  +
  +        protected int size() {
  +            // XXX this is bad luck, we need a global read lock just for the size :( :( :(
  +            lock(globalLock, READ);
  +            return super.size();
  +        }
  +
  +        protected void clear() {
  +            lock(globalLock, WRITE);
  +            super.clear();
  +        }
  +
  +        protected void dispose() {
  +            super.dispose();
  +            for (Iterator it = locks.iterator(); it.hasNext();) {
  +                MultiLevelLock lock = (MultiLevelLock) it.next();
  +                lock.release(this);
  +            }
  +        }
  +
  +        protected void finalize() throws Throwable {
  +            dispose();
  +            super.finalize();
  +        }
  +
  +        protected void lock(MultiLevelLock lock, int level) throws LockException {
  +            boolean acquired = false;
  +            try {
  +                acquired = lock.acquire(this, level, true, true, readTimeOut);
  +            } catch (InterruptedException e) {
  +                throw new LockException("Interrupted", LockException.CODE_INTERRUPTED, GLOBAL_LOCK_NAME);
  +            }
  +            if (!acquired) {
  +                throw new LockException("Timed out", LockException.CODE_TIMED_OUT, GLOBAL_LOCK_NAME);
  +            }
  +            locks.add(lock);
  +        }
  +    }
  +
   }
  
  
  
  1.1                  jakarta-commons-sandbox/transaction/src/java/org/apache/commons/transaction/memory/LockException.java
  
  Index: LockException.java
  ===================================================================
  /*
   * $Header: /home/cvs/jakarta-commons-sandbox/transaction/src/java/org/apache/commons/transaction/memory/LockException.java,v 1.1 2004/06/06 13:11:04 ozeigermann Exp $
   * $Revision: 1.1 $
   * $Date: 2004/06/06 13:11:04 $
   *
   * ====================================================================
   *
   * Copyright 1999-2002 The Apache Software Foundation 
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   *
   */
  
  package org.apache.commons.transaction.memory;
  
  
  /**
   * Exception displaying a lock problem in pessimistic transactions.
   * 
   * @author <a href="mailto:ozeigermann@apache.org">Oliver Zeigermann</a>
   * @version $Revision: 1.1 $
   * @see OptimisticMapWrapper
   */
  public class LockException extends RuntimeException /* FIXME Exception*/ {
  
      public static final int CODE_INTERRUPTED = 1;
      public static final int CODE_TIMED_OUT = 2;
      public static final int CODE_DEADLOCK_VICTIM = 3;
      
  	protected Object key;
      protected String reason;
      protected int code;
  	
  	public LockException(String reason, int code, Object key) {
          this.reason = reason;
  		this.key = key;
          this.code = code;
  	}
  }
  
  
  
  1.1                  jakarta-commons-sandbox/transaction/src/test/org/apache/commons/transaction/memory/PessimisticMapWrapperTest.java
  
  Index: PessimisticMapWrapperTest.java
  ===================================================================
  /*
   * $Header: /home/cvs/jakarta-commons-sandbox/transaction/src/test/org/apache/commons/transaction/memory/PessimisticMapWrapperTest.java,v 1.1 2004/06/06 13:11:04 ozeigermann Exp $
   * $Revision: 1.1 $
   * $Date: 2004/06/06 13:11:04 $
   *
   * ====================================================================
   *
   * Copyright 1999-2002 The Apache Software Foundation 
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   *
   */
  
  package org.apache.commons.transaction.memory;
  
  import junit.framework.*;
  
  import java.util.HashMap;
  import java.util.Map;
  import java.util.logging.*;
  
  import org.apache.commons.transaction.util.Jdk14Logger;
  import org.apache.commons.transaction.util.LoggerFacade;
  import org.apache.commons.transaction.util.RendezvousBarrier;
  
  /**
   * Tests for map wrapper. 
   *
   * @author <a href="mailto:ozeigermann@apache.org">Oliver Zeigermann</a>
   */
  public class PessimisticMapWrapperTest extends MapWrapperTest {
  
      private static final Logger logger = Logger.getLogger(PessimisticMapWrapperTest.class.getName());
      private static final LoggerFacade sLogger = new Jdk14Logger(logger);
  
      public static Test suite() {
          TestSuite suite = new TestSuite(PessimisticMapWrapperTest.class);
          return suite;
      }
  
      public static void main(java.lang.String[] args) {
          junit.textui.TestRunner.run(suite());
      }
  
      public PessimisticMapWrapperTest(String testName) {
          super(testName);
      }
  
      protected TransactionalMapWrapper getNewWrapper(Map map) {
          return new PessimisticMapWrapper(map, sLogger);
      }
  
      // XXX no need for this code, just to make clear those tests are run as well 
      public void testBasic() throws Throwable {
          super.testBasic();
      }
  
      public void testComplex() throws Throwable {
          super.testComplex();
      }
  
      public void testSets() throws Throwable {
          super.testSets();
      }
  
      public void testMulti() throws Throwable {
          logger.info("Checking concurrent transaction features");
  
          final Map map1 = new HashMap();
  
          final PessimisticMapWrapper txMap1 = (PessimisticMapWrapper) getNewWrapper(map1);
  
          final RendezvousBarrier beforeCommitBarrier =
              new RendezvousBarrier("Before Commit", 2, BARRIER_TIMEOUT, sLogger);
  
          final RendezvousBarrier afterCommitBarrier = new RendezvousBarrier("After Commit", 2, BARRIER_TIMEOUT, sLogger);
  
          Thread thread1 = new Thread(new Runnable() {
              public void run() {
                  txMap1.startTransaction();
                  txMap1.put("key1", "value2");
                  synchronized (txMap1) {
                      txMap1.commitTransaction();
                      report("value2", (String) txMap1.get("key1"));
                  }
              }
          }, "Thread1");
  
          txMap1.put("key1", "value1");
  
          txMap1.startTransaction();
  
          report("value1", (String) txMap1.get("key1"));
  
          thread1.start();
  
          // we have serializable as isolation level, that's why I will still see the old value
          report("value1", (String) txMap1.get("key1"));
  
          txMap1.put("key1", "value3");
  
          // after commit it must be our value
          synchronized (txMap1) {
              txMap1.commitTransaction();
              report("value3", (String) txMap1.get("key1"));
          }
      }
  
      public void testTxControl() throws Throwable {
          super.testTxControl();
      }
  
  }
  
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: commons-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-dev-help@jakarta.apache.org