简体   繁体   中英

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 (ie 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

maxMemory();
totalMemory();
freeMemory();

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, ie 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).

if you are trying to capture these attributes outside the program for performance tests; you might also wanna use Java Profilers. There are good profilers available out there. Java 6 also provides one to do these kinds of activities. for example J Profiler If you want more such tools; let me know.

Since Java 1.6 there's a set of tools allowing to monitor the JVM. One of them is jmap . You could take a look at it.

I am not quite sure how it applies to J2ME, but I would guess you could apply the same technique to the J2ME emulator on a computer (using full JVM, not a KVM).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM