[java] How to parse Heap Dump

Status
Not open for further replies.
Hello again --

I'm trying to show the higher ups that our codebase is not using objects correctly. We're making copies of immutable objects all over the place and its driving me mad. However, I have no 'proof' (i.e., metrics) to show the bosses that its a problem.

I just got an Out-of-Memory exception's Heap Dump of one particular program which tends toward OOMEs and I want to go through the thing, find all the Integer, String and what-not objects, get their values and compare them, showing the count of instances of exact copies as well as the memory allocated to them.

jhat is quite sluggish (there are 9.4 million object instances in this heap dump), NetBeans' heap viewer is more user-interactive, for digging into stuff manually.

I want to somehow parse this thing 'my way' or otherwise produce the 'report' I mention above.

Help?

- z -
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
this is useful, and will give you a good idea of what to target but a decent profiler should tell you all allocations in a run broken down by type and by location of allocation (i.e. mthod).

The resulting output logs tend to be massive but there's really nothing like it for breaking that down.

I'd look at using that to find the worst offenders, fixing them and then showing higher ups (a maximum of )two very simple charts.

1) time taken with/without your changes
2) memory used with/without your changes

One or both of these should be (based on your OP) very significant improvements.

These are improvements that you can *sell* to them. that the improvements are likely to make the code simpler is even better.
 
True. But I know that there are places where we needless create a new copy of Integer(1) when copying values (i.e., keys) from one object to another.

I also KNOW we have a memory leak in this particular module. It can just fumble along for days at a time at about 256MB of allocated heap. Then 'suddenly', the heap will grow and grow and grow until it hits the max size we have set (1600m!!!) and then crumble into dust (actually, it doesn't crumble into dust due to the shutdown semantics of this module -- it keeps trying to run -- keeps triggering further OOMEs -- and keeps trying to run...)

Anyhow, this heap snapshot is all I have that may/may not show wherein the problem lies.

I'm trying to figure out an 'easy' way to see what composite or collection types are creating/using all the primitive objects (Integer, Float, BigDecimal, etc.) being created.

I understand what I'm looking at (in the case of the NetBeans heap browser) but I don't know how to use it to the fullest -- it doesn't seem to organize data the way I'd like (root-set of objects and navigate out to the classes and sub-classes which make them up.)

Appreciate the thoughts.

(P.S. I've been tasked to MEASURE the current system, not to CHANGE and compare. With ~440K LOC amongst ~1K Java classfiles, changing this beast would be 'hard.' -- there's a lot of coupling between all this code, so a change in one area, ripples out to a lot... Yes, that's another thing I'm trying to change.)
 
ShuggyCoUk":7skory10 said:
If it happens only occasionaly it may be being masked by the runtimes built in interning of a subset of the Integers (-128 <-> 127 IIRC) so if you keep largely within those ranges your copies are silently eliminated (still costly but not in terms of memory) but going outside them screws you over.

Yep. And we're WAAAAY outside those bounds. I often find my thought process going down the rabbit hole -- if they cache -128 to 127, why not the rest of them ...

Trombone8vb":7skory10 said:
JVisualVM is included in recent JDK releases. It has a good heap dump viewer.

There is also the extremely powerful Eclipse Memory Analyzer, but you probably don't need anything that sophisticated.

John

It pretty much matches the capabilities of the NetBeans Heap Dump navigator. In fact, they look identical except for the NetBeans IDE not being wrapped around the Java VisualVM window.

Granted they're both good tools, I'm just having a hard time getting the information I want. "where are the big collections" ...
 

pyu

Ars Praefectus
5,108
Subscriptor
I've used JProfiler and over the lifetime of a running application, it allows me to trace which class occupies the most space on the heap and also the methods which are called the most often. Usually, this two run hand-in-hand.

I've encountered my fair share of OutOfMemoryExceptions which have really frustrated me and I am usually able to trace it to old legacy code which misbehaves when fed data it can't handle - usually due to algorithm in question doing something very silly - ever fed extremely small negative values to an algorithm which uses some weird bit representation to do numerical sorting? oh yeah...
 
zelmak":d48mg8pz said:
I also KNOW we have a memory leak in this particular module. It can just fumble along for days at a time at about 256MB of allocated heap. Then 'suddenly', the heap will grow and grow and grow until it hits the max size we have set (1600m!!!) and then crumble into dust (actually, it doesn't crumble into dust due to the shutdown semantics of this module -- it keeps trying to run -- keeps triggering further OOMEs -- and keeps trying to run...)
To me, "suddenly" makes it sound more like a logic bug on certain classes of input, rather than a conventional memory leak.
 
aliftedlorax":s4yy4a7p said:
zelmak":s4yy4a7p said:
I also KNOW we have a memory leak in this particular module. It can just fumble along for days at a time at about 256MB of allocated heap. Then 'suddenly', the heap will grow and grow and grow until it hits the max size we have set (1600m!!!) and then crumble into dust (actually, it doesn't crumble into dust due to the shutdown semantics of this module -- it keeps trying to run -- keeps triggering further OOMEs -- and keeps trying to run...)
To me, "suddenly" makes it sound more like a logic bug on certain classes of input, rather than a conventional memory leak.

I pretty sure you're right. But the accelerated use of memory (and complete lack of freeing said memory?) is triggered by this logic bug ... and when its triggered, the OOME isn't very nice that it actually happens directly in code along this module's code path so that a sensical stack trace can be generated. (The module has a total of 12 threads running -- some of which are the typical JVM threads -- any of which can allocate memory.)

And since this OOME happens rather rarely, its nigh impossible to capture. Which is why this heap dump is so important to me. I want to recreate the state of the heap at the crash so I can see which data structures exist, maybe record or object IDs so that I can trace back to the input records and see if there's something there that exercises a weird path thru the logic (you know, all that debugging stuff we do.)

Also and unfortunately, I'm working on a network where it is nearly impossible to bring in new software (at least in one's own lifetime), hence the request for help in parsing the file myself. The tools provided by Sun (jhat, jvisualvm) and NetBeans (Heap Dump) are great, but they're not really helping me find what I want to find through their GUIs. Unless, of course, that I don't how to get what I want out of them -- entirely possible.

Edit: What I'd REALLY like, is a proggie like SpaceMonger which uses a Treemap visualization to tell you where all the big objects are, let's you drill down into their component parts, etc.
 

cmannes

Ars Scholae Palatinae
836
Subscriptor++
zelmak":2em83em2 said:
Edit: What I'd REALLY like, is a proggie like SpaceMonger which uses a Treemap visualization to tell you where all the big objects are, let's you drill down into their component parts, etc.

Really that sounds like JProfiler. See some of the screenshots & descriptions at

http://www.ej-technologies.com/products ... snew6.html

I'm not trying to sell you anything. :) Just you seem to keep describing JProfiler.

EDIT: This screenshot for example http://www.ej-technologies.com/products ... ts_fsb.png
 

tripnotik

Smack-Fu Master, in training
89
Subscriptor++
zelmak":32zacfr8 said:
Edit: What I'd REALLY like, is a proggie like SpaceMonger which uses a Treemap visualization to tell you where all the big objects are, let's you drill down into their component parts, etc.

Isn't it exactly what Eclipse's Memory Analyser does? You can have a neat chart of "Biggest Objects by Retained Size", then you can drill down to see each object referenced by that object and so on. There's even an SQL-like query language to help you search through everything.
 
tripnotik":1c05p9bj said:
Isn't it exactly what Eclipse's Memory Analyser does? You can have a neat chart of "Biggest Objects by Retained Size", then you can drill down to see each object referenced by that object and so on. There's even an SQL-like query language to help you search through everything.

I don't have access to Eclipse's Memory Analysis tool, but the way NetBeans/JVisualVM and jhat show things are the classes ordered by instance count or total allocated memory. In my case, Integer is the most used (instance count) and largest user of space (allocated memory). They list these at the top of the 'histogram' and leave it to you to spelunk through the references to see which 'parent' object(s) refer to the Integer objects. In essence, the large composite objects which are comprised of these 'leaf' objects, aren't represented by their actual 'size' (self size + referenced objects.)

I'm not explaining this well, I know... Its still early for me and I haven't had my morning cup o' Mt Dew.

Off to meetings...
 

tripnotik

Smack-Fu Master, in training
89
Subscriptor++
zelmak":yjzm73bq said:
tripnotik":yjzm73bq said:
Isn't it exactly what Eclipse's Memory Analyser does? You can have a neat chart of "Biggest Objects by Retained Size", then you can drill down to see each object referenced by that object and so on. There's even an SQL-like query language to help you search through everything.

I don't have access to Eclipse's Memory Analysis tool, but the way NetBeans/JVisualVM and jhat show things are the classes ordered by instance count or total allocated memory. In my case, Integer is the most used (instance count) and largest user of space (allocated memory). They list these at the top of the 'histogram' and leave it to you to spelunk through the references to see which 'parent' object(s) refer to the Integer objects. In essence, the large composite objects which are comprised of these 'leaf' objects, aren't represented by their actual 'size' (self size + referenced objects.)

I'm not explaining this well, I know... Its still early for me and I haven't had my morning cup o' Mt Dew.

Off to meetings...

That's too bad that you can't have acces to Eclipse's tool, because it's far ahead of VisualVM (I don't know about NetBeans). What you're explaining sounds like the retained size (size of an object + all objects that are only accessible from it, or put in another way, the size of the memory that will be freed if the object is garbage collected). Eclipse's MAT will show you this value for each object. Also, for each object, you can also find in 1 click which objects have a reference to it.

I think you can find the top objects by retained size in VisualVM, but I never had the patience to let it finish because it was too slow when dealing with a large dump. Good luck in your debugging.
 

Redshift

Ars Scholae Palatinae
1,260
-- if they cache -128 to 127, why not the rest of them

Maybe someone tried to cache all 4 billion of them, at the application level, and that is the source of your memory leak.


Have you looked closely at the code indicated by the stack trace of the OOMEs? It it not necessarily the same code with the memory leak--but often is.
 
Redshift":3hv9asn7 said:
-- if they cache -128 to 127, why not the rest of them

Maybe someone tried to cache all 4 billion of them, at the application level, and that is the source of your memory leak.


Have you looked closely at the code indicated by the stack trace of the OOMEs? It it not necessarily the same code with the memory leak--but often is.

:) I know for a fact that some one of these classes I'm working with created some sort of object pool, but I can't for the life of me find the blasted thing again. I wouldn't put it past previous programmers to do that (edit: 'that' being creating an Integer cache) ... or allow an infinitely growing object pool ...

There is no 'usual' source of the OOMEs ... in this case, the one I captured, its a 'toCharArray()' inside a BigDecimal -- some sort of comparison operation is going on ... I'm looking there too.

My co-worker, who's been dealing with this much longer than I have, suspects its a large SQL query, but looking at the contents of the dump I have, I don't see obvious indications of that.

Further analysis ensues!
 
ShuggyCoUk":1qqi8z2i said:
BigDecimal

These are capable of growing to (memory and JVM bounded) arbitrary size. You may have some code paths that result in *huge* ones, made even worse if you try to then represent as a string/char array

Yes, I know that ... their use is questionable in the current code. Remarkably, this project has been using CVS since its inception, so I have some back history to look at. But, since the developer who changed portions of the code from using floats to BigDecimals died several years back, and there doesn't appear to be adequate documentation as to 'why', it appears that the reason for the change was due to the 'inexact' nature of floats and displaying them sanely in the GUI.

Since the values are grabbed using JDBC connections to Oracle, and uses the getFloat() method from the ResultSet and all of the 'floatValue()' and 'intValue()' calls against these BigIntegers, I'm sure that we don't really need the arbitrary length and precision of a 'BigDecimal', but a more exact representation of a floating point number -- integer-based math with an implied decimal point.

My feeling is that the original coders (working with Java 1.1/1.2) really didn't understand Java like I do now and were just doing the best they could with their background.

Stuff like this:

Code:
// SpecialTextField extends JTextField and has a special model 
// and input scheme which only allows digits to be entered thus
// only whole numbers are allowed
private final SpecialTextField idField = new SpecialTextField();

public int getKey() {
  int rtn = -1;  
  try { 
    rtn = idField.getValue();
  } catch (Throwable throwable) {
    // this is empty
  }
  return rtn;
}

elsewhere,

Code:
Vector keys = null;
if (somethingorother) {
  keys = new Vector();
  keys.add(BigDecimal.valueOf(getKey())); // this is the getKey() from above
}

// not much later, but the only use of 'keys' to the end of the method ...

if (somethingIsTrue) {
  for (int i = 0; i < keys.size(); i++) {
    someObject.setKey(new Integer(((BigDecimal) keys.get(i)).intValue());
  }
} else {
  for (int i = 0; i < keys.size(); i++) {
    someOtherObject.setKey(new Integer(((BigDecimal) keys.get(i)).intValue());
  }
}

  • Only one entry is ever added to the Vector keys, so why is it a vector?
  • Why in the world is the entry added to keys as a BigDecimal when the function returns an int?
  • Why in the world is it a BigDecimal when we're getting its value out as an int?
  • Why are we casting the int value back into an Integer? Oh, for passing the value as an Integer to setKey(). Yes, the code predates 1.5's autoboxing, but dayum?

This is the typical use for these BigDecimals ... holders for converting to whatever format is needed ... and for nicer, more stable display in GUI fields, columns, etc. As far as I've been able to find, no actual calculations are done with them, but there are a lot of compares.

Wacky stuff like this is what I contend with daily ... I'd like to just 'fix it' ... but the powers-that-be (i.e., the customer) isn't ready to commit to something which would require this much rewrite because 'it works' and they're looking at other solutions.
 

DogOnFire

Seniorius Lurkius
43
This is just intuition from personal experience:

Your plan to eliminate redundant BigDecimal -> Integer and Integer -> BigDecimal conversion will probably not make a noticeable difference.

In a normal business application, with typical ram sizes nowadays, it's almost impossible to create a noticeable memory leak by making extra copies of "small" objects such as Integers and integer-valued BigDecimals. Even a million Integers that could have been re-used instead of copied would only make 16 megabytes of memory usage.

What I would recommend you look for is code that keeps a reference to objects when it should not. Examples:

- static fields: See if the static field is holding onto a data structure that is not being used by the program any longer.
- fields on Singletons: This can have the same problem as static fields since the singleton lives forever.
- object caches: These can cause some object to be ineligible for garbage collection. If you find any, determine how large they might get, whether there is an expiration policy, etc.
- "implicit" object caches: Many technologies (such as Hibernate) have a built-in cache; these can be hard to find because you can't locate such caches by inspecting the source code for your own application.

One thing to try is that you can put in calls to Runtime.getRuntime().freeMemory() to allow the program to monitor its own memory usage and to test what effects a particular method call has on memory usage.

For example, in your second code block, you can make one call to get the free memory at entrance to the function, and another call at exit, and subtract to find out how much memory impact there is in that function. If it is significant, then that's ground for rewriting the function to remove the copies. If not, then you know to look elsewhere.
 
I agree that this sounds like unexpected input causing sudden memory growth rather than a leak. Is there a way you can replay your transactions in a controlled environment, or add logging to the start/end of transactions? Can you increase your maximum heap size and see if the memory spikes and then returns to normal?

Have you turned on verbose garbage collection and logged the results to file?

Have you tried using JConsole / jstack to see what the application is doing when the problem occurs?
 
Sorry to ressurect a really old thread, but I discovered at least one data input that will reliably crash our JVM with an OOME.

Our process attempts to correlate new input data to in-system data by comparing various data items in the input against the same items in the database. This speeds downstream work by 'binning' the input. This is done with a simple SELECT query with applicable fields/columns. This is entirely data driven (by the input).

What happened with this given input was that, of the eight to ten selective fields (I'd have to go back and actually count--irrelevant at this point), there was only one which was filled in on the input data (not entirely abnormal from our upstream data feed) but the field which was filled in was already overly general in the first place. THEN, the correlator query ignores the first character (of this two character field) and replaced it with a '%' in a LIKE clause.

This generated over 900,000 results.

Which were then converted into their domain objects (of which instead of float or double, using BigDecimal) and stuffed into an ArrayList. Further processing then duplicates that ArrayList, modifying the contents here and there based on further queries (which -- I just realized I haven't further sussed out -- I'm guessing are really crappy WHERE key in ( <list of keys from the original ArrayList> ) thus creating new objects, meanwhile copying the new, modified items to the new ArrayList. And it does this processing step three times.

So, yeah, a mess.

Thought some of you might be interested or curious to see how things worked out.

<mode zombie=off>
 
Status
Not open for further replies.