1 8 9 package org.apache.beehive.netui.util.internal.concurrent; 10 11 import java.security.AccessController ; 12 import java.security.PrivilegedAction ; 13 14 29 final class Utils { 30 31 private final static NanoTimer nanoTimer; 32 private final static String providerProp = 33 "org.apache.beehive.netui.util.concurrent.NanoTimerProvider"; 34 35 static { 36 NanoTimer timer = null; 37 try { 38 String nanoTimerClassName = (String ) 39 AccessController.doPrivileged(new PrivilegedAction () { 40 public Object run() { 41 return System.getProperty(providerProp); 42 } 43 }); 44 if (nanoTimerClassName != null) { 45 Class cls = Class.forName(nanoTimerClassName); 46 timer = (NanoTimer) cls.newInstance(); 47 } 48 } 49 catch (Exception e) { 50 System.err.println("WARNING: unable to load Perf provider; " + 51 "switching to a default"); 52 e.printStackTrace(); 53 } 54 55 if (timer == null) { 56 try { 57 timer = new SunPerfProvider(); 58 } 59 catch (Throwable e) {} 60 } 61 62 if (timer == null) { 63 timer = new MillisProvider(); 64 } 65 66 nanoTimer = timer; 67 } 68 69 private Utils() {} 70 71 96 public static long nanoTime() { 97 return nanoTimer.nanoTime(); 98 } 99 100 190 public static long awaitNanos(Condition cond, long nanosTimeout) 191 throws InterruptedException 192 { 193 if (nanosTimeout <= 0) return nanosTimeout; 194 long now = nanoTime(); 195 cond.await(nanosTimeout, TimeUnit.NANOSECONDS); 196 return nanosTimeout - (nanoTime() - now); 197 } 198 199 private static final class SunPerfProvider implements NanoTimer { 200 final sun.misc.Perf perf; 201 final long multiplier, divisor; 202 SunPerfProvider() { 203 perf = (sun.misc.Perf) 204 AccessController.doPrivileged(new PrivilegedAction () { 205 public Object run() { 206 return sun.misc.Perf.getPerf(); 207 } 208 }); 209 long numerator = 1000000000; 211 long denominator = perf.highResFrequency(); 212 long gcd = gcd(numerator, denominator); 213 this.multiplier = numerator / gcd; 214 this.divisor = denominator / gcd; 215 } 216 public long nanoTime() { 217 long ctr = perf.highResCounter(); 218 219 223 return ((ctr / divisor) * multiplier) + 224 (ctr % divisor) * multiplier / divisor; 225 226 230 } 251 } 252 253 private static final class MillisProvider implements NanoTimer { 254 MillisProvider() {} 255 public long nanoTime() { 256 return System.currentTimeMillis() * 1000000; 257 } 258 } 259 260 private static long gcd(long a, long b) { 261 long r; 262 while (b>0) { r = a % b; a = b; b = r; } 263 return a; 264 } 265 266 } 267 | Popular Tags |