1
2
3
4
5 package oshi.software.common;
6
7 import static oshi.util.Memoizer.defaultExpiration;
8 import static oshi.util.Memoizer.memoize;
9
10 import java.util.function.Supplier;
11
12 import oshi.annotation.concurrent.ThreadSafe;
13 import oshi.software.os.OSProcess;
14
15
16
17
18
19
20 @ThreadSafe
21 public abstract class AbstractOSProcess implements OSProcess {
22
23 private final Supplier<Double> cumulativeCpuLoad = memoize(this::queryCumulativeCpuLoad, defaultExpiration());
24
25 private int processID;
26
27 protected AbstractOSProcess(int pid) {
28 this.processID = pid;
29 }
30
31 @Override
32 public int getProcessID() {
33 return this.processID;
34 }
35
36 @Override
37 public double getProcessCpuLoadCumulative() {
38 return cumulativeCpuLoad.get();
39 }
40
41 private double queryCumulativeCpuLoad() {
42 return getUpTime() > 0d ? (getKernelTime() + getUserTime()) / (double) getUpTime() : 0d;
43 }
44
45 @Override
46 public double getProcessCpuLoadBetweenTicks(OSProcess priorSnapshot) {
47 if (priorSnapshot != null && this.processID == priorSnapshot.getProcessID()
48 && getUpTime() > priorSnapshot.getUpTime()) {
49 return (getUserTime() - priorSnapshot.getUserTime() + getKernelTime() - priorSnapshot.getKernelTime())
50 / (double) (getUpTime() - priorSnapshot.getUpTime());
51 }
52 return getProcessCpuLoadCumulative();
53 }
54
55 @Override
56 public String toString() {
57 StringBuilder builder = new StringBuilder("OSProcess@");
58 builder.append(Integer.toHexString(hashCode()));
59 builder.append("[processID=").append(this.processID);
60 builder.append(", name=").append(getName()).append(']');
61 return builder.toString();
62 }
63 }