View Javadoc
1   /*
2    * Copyright 2020-2022 The OSHI Project Contributors
3    * SPDX-License-Identifier: MIT
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   * A process is an instance of a computer program that is being executed. It contains the program code and its current
17   * activity. Depending on the operating system (OS), a process may be made up of multiple threads of execution that
18   * execute instructions concurrently.
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  }