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.Locale;
11 import java.util.function.Supplier;
12
13 import oshi.annotation.concurrent.ThreadSafe;
14 import oshi.software.os.OSThread;
15
16
17
18
19 @ThreadSafe
20 public abstract class AbstractOSThread implements OSThread {
21
22 private final Supplier<Double> cumulativeCpuLoad = memoize(this::queryCumulativeCpuLoad, defaultExpiration());
23
24 private final int owningProcessId;
25
26 protected AbstractOSThread(int processId) {
27 this.owningProcessId = processId;
28 }
29
30 @Override
31 public int getOwningProcessId() {
32 return this.owningProcessId;
33 }
34
35 @Override
36 public double getThreadCpuLoadCumulative() {
37 return cumulativeCpuLoad.get();
38 }
39
40 private double queryCumulativeCpuLoad() {
41 return getUpTime() > 0d ? (getKernelTime() + getUserTime()) / (double) getUpTime() : 0d;
42 }
43
44 @Override
45 public double getThreadCpuLoadBetweenTicks(OSThread priorSnapshot) {
46 if (priorSnapshot != null && owningProcessId == priorSnapshot.getOwningProcessId()
47 && getThreadId() == priorSnapshot.getThreadId() && getUpTime() > priorSnapshot.getUpTime()) {
48 return (getUserTime() - priorSnapshot.getUserTime() + getKernelTime() - priorSnapshot.getKernelTime())
49 / (double) (getUpTime() - priorSnapshot.getUpTime());
50 }
51 return getThreadCpuLoadCumulative();
52 }
53
54 @Override
55 public String toString() {
56 return "OSThread [threadId=" + getThreadId() + ", owningProcessId=" + getOwningProcessId() + ", name="
57 + getName() + ", state=" + getState() + ", kernelTime=" + getKernelTime() + ", userTime="
58 + getUserTime() + ", upTime=" + getUpTime() + ", startTime=" + getStartTime()
59 + ", startMemoryAddress=0x" + String.format(Locale.ROOT, "%x", getStartMemoryAddress())
60 + ", contextSwitches=" + getContextSwitches() + ", minorFaults=" + getMinorFaults() + ", majorFaults="
61 + getMajorFaults() + "]";
62 }
63 }