1 7 package org.jboss.cache.optimistic; 8 9 import junit.framework.Assert; 10 import org.apache.commons.logging.Log; 11 import org.apache.commons.logging.LogFactory; 12 import org.jboss.cache.CacheImpl; 13 import org.jboss.cache.Fqn; 14 15 import javax.transaction.TransactionManager ; 16 17 22 public class ThreadedCacheAccessTest extends AbstractOptimisticTestCase 23 { 24 private static final Log log = LogFactory.getLog(ThreadedCacheAccessTest.class); 25 private final int numThreads = 5; 27 private final int numLoopsPerThread = 25; 29 private final int writeFrequency = 5; 31 private final int minSleep = 0, maxSleep = 100; 33 34 private final Fqn fqn = Fqn.fromString("/a/b"); 35 private final String key = "key", value = "value"; 36 37 private CacheImpl cache; 38 private WorkerThread[] threads; 39 40 public ThreadedCacheAccessTest(String name) 41 { 42 super(name); 43 } 44 45 protected void tearDown() 46 { 47 super.tearDown(); 48 destroyCache(cache); 49 } 50 51 public void testThreadedMostlyReads() throws Exception 52 { 53 cache = createCache(); 54 56 cache.put(fqn, key, value); 57 58 threads = new WorkerThread[numThreads]; 59 60 for (int i = 0; i < numThreads; i++) 61 { 62 threads[i] = new WorkerThread(); 63 threads[i].start(); 64 } 65 66 for (int i = 0; i < numThreads; i++) 67 { 68 threads[i].join(); 69 } 70 71 for (int i = 0; i < numThreads; i++) 73 { 74 Assert.assertTrue("Thread threw an exception!", threads[i].success); 75 } 76 } 77 78 public class WorkerThread extends Thread 79 { 80 public boolean success = true; 81 82 public void run() 83 { 84 log.debug(getName() + " starting up ... "); 85 for (int j = 0; j < numLoopsPerThread; j++) 86 { 87 TransactionManager tm = cache.getTransactionManager(); 88 try 89 { 90 tm.begin(); 91 cache.get(fqn, key); 93 if (j % writeFrequency == 0) 94 { 95 cache.put(fqn, key, value + j); 96 } 97 tm.commit(); 98 } 99 catch (Exception e) 100 { 101 log.error("Caught Exception!", e); 102 Assert.assertTrue("Caught Exception!", false); 103 success = false; 104 try 105 { 106 tm.rollback(); 107 } 108 catch (Exception e2) 109 { 110 log.error("Rollback failed!", e2); 111 } 112 break; 113 } 114 randomSleep(minSleep, maxSleep); 115 } 116 } 117 } 118 } 119 | Popular Tags |