1 28 29 package com.caucho.util; 30 31 import com.caucho.log.Log; 32 33 import java.util.logging.Level ; 34 import java.util.logging.Logger ; 35 36 public class CpuUsage { 37 static Logger log = Log.open(CpuUsage.class); 38 39 private static CauchoNative jni; 40 private static boolean triedLoading; 41 42 private int pid; 43 44 private long time; 45 private long interval; 46 47 private long userTime; 48 private long systemTime; 49 50 private CpuUsage() 51 { 52 } 53 54 public static synchronized CpuUsage create() 55 { 56 if (jni == null && ! triedLoading) { 57 triedLoading = true; 58 try { 59 jni = CauchoNative.create(); 60 } catch (Throwable e) { 61 log.log(Level.FINE, e.toString(), e); 62 } 63 } 64 65 CpuUsage usage = new CpuUsage(); 66 67 if (jni == null) 68 return usage; 69 70 usage.update(Alarm.getCurrentTime()); 71 72 return usage; 73 } 74 75 public void update(long now) 76 { 77 time = now; 78 79 if (jni == null) 80 return; 81 82 synchronized (jni) { 83 jni.calculateUsage(); 84 pid = jni.getPid(); 85 userTime = (long) (jni.getUserTime() * 1000); 86 systemTime = (long) (jni.getSystemTime() * 1000); 87 } 88 } 89 90 public void copy(CpuUsage source) 91 { 92 pid = source.pid; 93 time = source.time; 94 95 userTime = source.userTime; 96 systemTime = source.systemTime; 97 } 98 99 public void clear() 100 { 101 pid = -1; 102 time = 0; 103 interval = 0; 104 userTime = 0; 105 systemTime = 0; 106 } 107 108 public void add(CpuUsage base, CpuUsage source) 109 { 110 if (pid == -1) { 111 pid = source.getPid(); 112 time = source.getTime(); 113 interval = time - base.getTime(); 114 } 115 else if (pid == source.getPid()) 116 return; 117 118 userTime += source.getUserTime() - base.getUserTime(); 119 systemTime += source.getSystemTime() - base.getSystemTime(); 120 } 121 122 public int getPid() 123 { 124 return pid; 125 } 126 127 public long getTime() 128 { 129 return time; 130 } 131 132 public long getInterval() 133 { 134 return interval; 135 } 136 137 public long getUserTime() 138 { 139 return userTime; 140 } 141 142 public long getSystemTime() 143 { 144 return systemTime; 145 } 146 147 boolean setUser(String user, String group) 148 throws Exception 149 { 150 if (jni == null) 151 return false; 152 153 else if (user != null) { 154 synchronized (jni) { 155 return jni.setUser(user, group); 156 } 157 } 158 else 159 return false; 160 } 161 } 162 163 164 | Popular Tags |