determining java memory usage

2020-01-31 03:56发布

Hmmm. Is there a primer anywhere on memory usage in Java? I would have thought Sun or IBM would have had a good article on the subject but I can't find anything that looks really solid. I'm interested in knowing two things:

  1. at runtime, figuring out how much memory the classes in my package are using at a given time
  2. at design time, estimating general memory overhead requirements for various things like:
    • how much memory overhead is required for an empty object (in addition to the space required by its fields)
    • how much memory overhead is required when creating closures
    • how much memory overhead is required for collections like ArrayList

I may have hundreds of thousands of objects created and I want to be a "good neighbor" to not be overly wasteful of RAM. I mean I don't really care whether I'm using 10% more memory than the "optimal case" (whatever that is), but if I'm implementing something that uses 5x as much memory as I could if I made a simple change, I'd want to use less memory (or be able to create more objects for a fixed amount of memory available).

I found a few articles (Java Specialists' Newsletter and something from Javaworld) and one of the builtin classes java.lang.instrument.getObjectSize() which claims to measure an "approximation" (??) of memory use, but these all seem kind of vague...

(and yes I realize that a JVM running on two different OS's may be likely to use different amounts of memory for different objects)

标签: java memory
8条回答
做个烂人
2楼-- · 2020-01-31 04:47

I've used the profiler that comes with newer versions of Netbeans a couple of times and it works very well, supplying you with a ton of information about memory usage and runtime of your programs. Definitely a good place to start.

查看更多
够拽才男人
3楼-- · 2020-01-31 04:50

If you are using a pre 1.5 VM - You can get the approx size of objects by using serialization. Be warned though.. this can require double the amount of memory for that object.

查看更多
登录 后发表回答