1 5 package org.h2.test.unit; 6 7 import java.util.Random ; 8 9 import org.h2.test.TestBase; 10 import org.h2.util.StringCache; 11 12 public class TestStringCache extends TestBase { 13 14 public static void main(String [] args) throws Exception { 15 new TestStringCache().runBenchmark(); 16 } 17 18 private void runBenchmark() throws Exception { 19 returnNew = false; 20 for(int i=0; i<6; i++) { 21 useIntern = (i % 2) == 1; 22 long time = System.currentTimeMillis(); 23 testSingleThread(100000); 24 time = System.currentTimeMillis()-time; 25 System.out.println(time + " ms (useIntern=" + useIntern+")"); 26 } 27 28 } 29 30 private Random random = new Random (1); 31 private String [] some = new String [] { null, "", "ABC", "this is a medium sized string", "1", "2"}; 32 private volatile boolean stop; 33 private boolean returnNew; 34 private boolean useIntern; 35 36 public void test() throws Exception { 37 returnNew = true; 38 StringCache.clearCache(); 39 testSingleThread(getSize(5000, 20000)); 40 testMultiThreads(); 41 returnNew = false; 42 StringCache.clearCache(); 43 testSingleThread(getSize(5000, 20000)); 44 testMultiThreads(); 45 } 46 47 String randomString() { 48 if(random.nextBoolean()) { 49 String s = some[random.nextInt(some.length)]; 50 if(s != null && random.nextBoolean()) { 51 s = new String (s); 52 } 53 return s; 54 } else { 55 int len = random.nextBoolean() ? random.nextInt(1000) : random.nextInt(10); 56 StringBuffer buff = new StringBuffer (len); 57 for(int i=0; i<len; i++) { 58 buff.append(random.nextInt(0xfff)); 59 } 60 return buff.toString(); 61 } 62 } 63 64 void testString() { 65 String a = randomString(); 66 if(returnNew) { 67 String b = StringCache.getNew(a); 68 try { 69 check(a, b); 70 } catch (Exception e) { 71 TestBase.logError("error", e); 72 } 73 if(a != null && a == b && a.length()>0) { 74 throw new Error ("a=" + System.identityHashCode(a) + " b=" + System.identityHashCode(b)); 75 } 76 } else { 77 String b; 78 if(useIntern) { 79 b = a == null ? null : a.intern(); 80 } else { 81 b = StringCache.get(a); 82 } 83 try { 84 check(a, b); 85 } catch (Exception e) { 86 TestBase.logError("error", e); 87 } 88 } 89 } 90 91 private void testSingleThread(int len) throws Exception { 92 for(int i=0; i<len; i++) { 93 testString(); 94 } 95 } 96 97 private void testMultiThreads() throws Exception { 98 int threadCount = getSize(3, 100); 99 Thread [] threads = new Thread [threadCount]; 100 for(int i=0; i<threadCount; i++) { 101 Thread t = new Thread (new Runnable () { 102 public void run() { 103 while(!stop) { 104 testString(); 105 } 106 } 107 }); 108 threads[i] = t; 109 } 110 for(int i=0; i<threadCount; i++) { 111 threads[i].start(); 112 } 113 int wait = getSize(200, 2000); 114 Thread.sleep(wait); 115 stop = true; 116 for(int i=0; i<threadCount; i++) { 117 threads[i].join(); 118 } 119 } 120 121 } 122 | Popular Tags |