1 5 package org.h2.util; 6 7 import java.lang.ref.WeakReference ; 8 9 import org.h2.engine.Constants; 10 11 public class StringCache { 12 private static final boolean ENABLED = true; 13 private static WeakReference weakCache = new WeakReference (null); 14 15 18 42 47 public static String get(String s) { 49 if (!Constants.OBJECT_CACHE || !ENABLED) { 50 return s; 51 } 52 if (s == null) { 53 return s; 54 } else if (s.length() == 0) { 55 return ""; 56 } 57 String [] cache = (String []) weakCache.get(); 58 int hash = s.hashCode(); 59 if (cache == null) { 60 cache = new String [Constants.OBJECT_CACHE_SIZE]; 61 weakCache = new WeakReference (cache); 62 } 63 int index = hash & (Constants.OBJECT_CACHE_SIZE - 1); 64 String cached = cache[index]; 65 if (cached != null) { 66 if (s.equals(cached)) { 67 return cached; 69 } 70 } 71 cache[index] = s; 72 return s; 73 } 74 75 public static String getNew(String s) { 76 if (!Constants.OBJECT_CACHE || !ENABLED) { 77 return s; 78 } 79 if (s == null) { 80 return s; 81 } else if (s.length() == 0) { 82 return ""; 83 } 84 String [] cache = (String []) weakCache.get(); 85 int hash = s.hashCode(); 86 if (cache == null) { 87 cache = new String [Constants.OBJECT_CACHE_SIZE]; 88 weakCache = new WeakReference (cache); 89 } 90 int index = hash & (Constants.OBJECT_CACHE_SIZE - 1); 91 String cached = cache[index]; 92 if (cached != null) { 93 if (s.equals(cached)) { 94 return cached; 96 } 97 } 98 s = new String (s); 100 cache[index] = s; 101 return s; 102 } 103 104 public static void clearCache() { 105 weakCache = new WeakReference (null); 106 } 107 108 } 109 | Popular Tags |