Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check how much resources a java program uses?

How do I check how much resources a java program uses?

In java it is quite easy to create a big nice program that does practically everything you want it to, but a little side effect is that is also very easy to indirectly allocate to much memory and cpu cycles by mistake (i.e. let's just use "new" a couple of times in the wrong place).

And if the program are supposed to run in a environment with very limited amount of resources, let's say something embedded or maybe a mobile phone (J2ME, Android etc etc), it is crucial to know how resource hungry your program is.

Note: Since my main focus has been c the last years I could be missing something very simple here, so please don't assume to much ;)

Thanks Johan

like image 372
Johan Avatar asked Dec 30 '22 21:12

Johan


2 Answers

maxMemory();
totalMemory();
freeMemory();
like image 70
Chris Klepeis Avatar answered Jan 08 '23 23:01

Chris Klepeis


You appear to be somewhat confused about what you really need. In your question I sense some uneasiness about "how many resources will Java gobbly up behind my back to bite me later?".

The answer to this is, to paraphrase Douglas Adams: "Dont' panic!" :-).

Seriously, Java does not necessarily use much more resources than a "native" application, so you probably need not worry.

A quick rundown:

  • Java programs will have a fixed memory overhead because of the JVM, i.e. even a trivial program will eat a few MB of memory. This however is will not grow for more complex software, so it's not usually a problem in practice. Also, several Java VMs running in parallel will share much of the RAM.
  • CPU: In general, a Java program will use the same CPU time as an equivalent native program. There's not fundamental reason why Java would need more. Garbage collection does have some overhead, but it's not usually significant (and manual memory management also has an overhead).
  • That said, things like accidental object retention or unneccessarily large objects can cause memory problems. But that's a problem you tackle when it arises.

Short version: Don't worry, just do as you always do: Make it run, make it run correctly, make it run fast (by profiling).

like image 45
sleske Avatar answered Jan 09 '23 00:01

sleske