1 package org.jboss.cache.interceptors; 2 3 import org.apache.commons.logging.Log; 4 import org.apache.commons.logging.LogFactory; 5 6 import javax.transaction.RollbackException ; 7 import javax.transaction.Synchronization ; 8 import javax.transaction.SystemException ; 9 import javax.transaction.Transaction ; 10 import java.util.HashMap ; 11 import java.util.Iterator ; 12 import java.util.LinkedList ; 13 import java.util.Map ; 14 15 25 public class OrderedSynchronizationHandler implements Synchronization { 26 Transaction tx=null; 27 LinkedList handlers=new LinkedList (); 28 29 30 static Map instances=new HashMap (); 31 32 static Log log=LogFactory.getLog(OrderedSynchronizationHandler.class); 33 34 35 private OrderedSynchronizationHandler(Transaction tx) { 36 this.tx=tx; 37 } 38 39 44 public static OrderedSynchronizationHandler getInstance(Transaction tx) throws SystemException , RollbackException { 45 OrderedSynchronizationHandler retval=(OrderedSynchronizationHandler)instances.get(tx); 46 if(retval != null) return retval; 47 retval=new OrderedSynchronizationHandler(tx); 48 tx.registerSynchronization(retval); 49 instances.put(tx, retval); 50 return retval; 51 } 52 53 54 public void registerAtHead(Synchronization handler) { 55 register(handler, true); 56 } 57 58 public void registerAtTail(Synchronization handler) { 59 register(handler, false); 60 } 61 62 void register(Synchronization handler, boolean head) { 63 if(handler != null && !handlers.contains(handler)) { 64 if(head) 65 handlers.addFirst(handler); 66 else 67 handlers.addLast(handler); 68 } 69 } 70 71 public void beforeCompletion() { 72 for(Iterator it=handlers.iterator(); it.hasNext();) { 73 Synchronization sync=(Synchronization )it.next(); 74 sync.beforeCompletion(); 75 } 76 } 77 78 public void afterCompletion(int status) { 79 for(Iterator it=handlers.iterator(); it.hasNext();) { 80 Synchronization sync=(Synchronization )it.next(); 81 try { 82 sync.afterCompletion(status); 83 } 84 catch(Throwable t) { 85 log.error("failed calling afterCompletion() on " + sync, t); 86 } 87 } 88 89 instances.remove(tx); 91 } 92 93 public String toString() { 94 StringBuffer sb=new StringBuffer (); 95 sb.append("tx=" + tx + ", handlers=" + handlers); 96 return sb.toString(); 97 } 98 } 99 | Popular Tags |