-1

I have a simple example with one method "complexCalculation()":

class LoadCpuSolve{

    static void complexСalculation(){
        // Complexs calculations here...
    }

    public static void main(String... args){
        // Start complex calculations
        complexСalculation();

        // Information about cpu load here...
        System.out.println("While method execute, CPU load on" + valueCpuLoad+"%");
    }
}
  1. Can it be done?
  2. How can I do it programmaticaly? Thank you.
Tomas
  • 1,567
  • 3
  • 21
  • 38
  • You may consider using **Profiler** programs. There is even one delivered with your `Java`. Their purpose is to analyze exactly such things. – Zabuzard Oct 21 '17 at 19:48
  • Can you explain why do you want to do it? I'm not sure whether you have understood correctly what CPU load means. (EDIT: I'm also not realy sure about it but I doubt that such value makes sense there.) – JojOatXGME Oct 21 '17 at 19:50
  • @JojOatXGME, it's need for my work. – Tomas Oct 21 '17 at 19:53
  • @Zabuza, I need to do this programmatically. – Tomas Oct 21 '17 at 19:54
  • @JojOatXGME, i am very glad for your answer, but, if you know how to do it programmaticaly or what i need to use for it, please, write me. – Tomas Oct 21 '17 at 19:56
  • You may research a bit before asking questions. A small google search with *"java access cpu load"* yield: [How do I monitor the computer's CPU, memory, and disk usage in Java?](https://stackoverflow.com/questions/47177/how-do-i-monitor-the-computers-cpu-memory-and-disk-usage-in-java) and [How to get percentage of CPU usage of OS from java](https://stackoverflow.com/questions/18489273/how-to-get-percentage-of-cpu-usage-of-os-from-java) – Zabuzard Oct 21 '17 at 19:56
  • Possible duplicate of [How to get percentage of CPU usage of OS from java](https://stackoverflow.com/questions/18489273/how-to-get-percentage-of-cpu-usage-of-os-from-java). – Zabuzard Oct 21 '17 at 19:56
  • @Zabuza, thanx you, but it's not duplicate! – Tomas Oct 21 '17 at 19:59
  • 1
    That's fine but then please clearly state what your research yield and why you think that your question is not duplicate to that. For me it looks like it is a duplicate since it answers how to access the *CPU load* from within Java. So you need to clarify such things, ideally before posting the question. – Zabuzard Oct 21 '17 at 20:01
  • First, I don't think there is a simple solution. I think you have to use some operating system specific API. Beside that, do you want to check whether you run too much I/O operations in `complexСalculation()`? In other terms, do you want to check whether I/O or CPU is your bottleneck? Otherwise, I don't see the meaning behind this value. As far as I know, when you are not doing any I/O, the load of the current CPU core/thread should always be near 100% while running this function. – JojOatXGME Oct 21 '17 at 20:02
  • @Zabuza, it's need for my work. I was told to show how loads the CPU my program at run time. And I didn't know how to write correctly. – Tomas Oct 21 '17 at 20:04
  • Java itself has no way to access that. All possible solutions use some calls to the OS (go outside of Java and *return*). For example you can execute commands on the console from within Java and read the returned value. Or you can use stuff like `JNI` to access the OS interfaces from within Java. However this is possibly so advanced that you should instead just use a library. – Zabuzard Oct 21 '17 at 20:08
  • @Zabuza, What libraries I can use? There is an example? – Tomas Oct 21 '17 at 20:09
  • Yeah, the **linked duplicates** list some libraries and solutions. – Zabuzard Oct 21 '17 at 20:10

2 Answers2

2

If you are using Java 7 or above, you can fetch the MBeanServer.

MBeanServer server = ManagementFactory.getPlatformMBeanServer();

Once you have the server, you can query the server OperatingSystem MXBean:

ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");

Once you have the ObjectName, you can query different attributes of OS. For example SystemCpuLoad,

AttributeList attrs = server.getAttributes(name, new String[]{"SystemCpuLoad"});

The value of the attribute can be retrieved by the following code,

 Object value = null;
 if (!attrs.isEmpty()) {
     Attribute att = (Attribute) attrs.get(0);
     value = att.getValue();
 }

Here is a complete example,

     public class LoadCpuSolve {

        static void complexСalculation() {
            // Complexs calculations here...
            try {
                Thread.currentThread().sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public static Object getValue(MBeanServer server, ObjectName name,
            String attrName) throws ReflectionException, InstanceNotFoundException {
            AttributeList attrs =
                server.getAttributes(name, new String[]{attrName});

            Object value = null;
            if (!attrs.isEmpty()) {
                Attribute att = (Attribute) attrs.get(0);
                value = att.getValue();
            }

            return value;
        }

        public static void main(
            String... args) throws Exception
            complexСalculation();

            MBeanServer server = ManagementFactory.getPlatformMBeanServer();
            ObjectName
                name = ObjectName.getInstance("java.lang:type=OperatingSystem");

            System.out.println(
                "While method execute, process CPU load on " + getValue(server, name,
                       "ProcessCpuLoad"));
            System.out.println(
                "While method execute, process CPU time on " + getValue(server, name,
                        "ProcessCpuTime"));
            System.out.println(
                "While method execute, system CPU load on " + getValue(server, name,
                        "SystemCpuLoad"));
        }
   }
Indra Basak
  • 7,124
  • 1
  • 26
  • 45
  • Nice answer! Thank you!!! – Tomas Oct 21 '17 at 21:59
  • @Tomas You are welcome. – Indra Basak Oct 21 '17 at 22:09
  • @IndraBasak do you know if this way retrieving CPU load is container aware, simply put if I have a java process running in k8s pod will this work? – Riddle Jun 29 '21 at 00:47
  • @Riddle It will probably work but it's not the best way to get systems metrics for k8s environment unless you are able to add other dimensions, e.g, container name, pod name, etc. The way we did for k8s environment is to generate the metrics regular way and then exporting to Prometheus. Prometheus collects dimensions. – Indra Basak Jun 29 '21 at 02:30
0

I'd expect that Java JVM TI comes with such functionality, because profiling tools also do often use this API. But it won't be that easy to integrate support for that, and it if's required that java classes are instrumentalized for that, performance will get down.

See here: https://docs.oracle.com/javase/7/docs/technotes/guides/jvmti/index.html

Christoph Bimminger
  • 1,006
  • 7
  • 25