How to determine what classes are causing Finalizer memory leak - java

I am using yourkit java profiler to try and determine where my memory leak is coming from. I think it is from a large number of java.lang.ref.finalizer objects not being collected/processed fast enough. None of the code I have written implements the finalize method, but I am using several libraries that may. Is there a way in yourkit or other means to determine what objects are not being finalized?

Related

java eliminating garbage generation

Suppose we have java task that is working in isolation and we are able to monitor it using visualvm... and we notice continuous garbage creation and periodic gc like this.
How do we detect what exactly is causing this issue
is there a way to see which method execution is generating garbage? how do we see where the garbage comes from?
yes we can see what objects exactly are allocating memory, but thats not helpful... i believe lot of objects are created and garbaged later, but i cant figure out where that happens and what exactly causes this...
How do we do this usually? what tools to use? any links to topics about this are appreciated
NOTE the problem here is not the GC parameter optimization, but rather the code optimization, we want to eliminate unnecessary object creation, maybe use primitives instead etc...
The easiest way is to use tool like JProfiler and record allocations. The "Allocation HotSpot" view will show in which method your application is allocating the objects. More details can be found here
When you cannot use profiler another approach is to take a heapdump and investigate the objects it contains. Then based on this information assume in which method they are instantiated.
I would suggest install VisualGC plugin in jvisualvm. It will give you very good idea about number of small and full GCs happening.
If you are looking for garbage collected objects and possible chance of memory leaks than you should inspect heap dump at two different instances of your code workflow.

Find out how much RAM is used by Thread

I would like to know how to find out how much RAM is consumed by certain Threads.
There are in my program about 15 classes, each is running in own Thread.
So how can I discover how much RAM is used by Thread1, Thread2, ... Thread15? Is there any method for this?
Thanks for replies!
The short answer is that all dynamicially allocated memory (heap) is shared by all threads unless you use Java's ThreadLocal class to declare variables that are local only to the thread.
In fact, the traditional Java memory model of shared data amongst threads (when not using ThreadLocal) is what makes threading so powerful for memory sharing across threads.
As sk4l mentioned there is a getThreadAllocatedBytes method of ThreadMXBean method if your JVM supports it, but keep in mind this is typically just an approximate value.
Lastly, most recent versions of the Oracle JDK and OpenJDK include jconsole and JDK 6u7 and later include VisualVM either of which you can use to attach to your process and see information about memory and threads.
Memory usage depends on JVM version and the OS.
All threads share a common heap. They all have their own stack, which usually is 512KB.
There are a couple of ways to see per thread memory usage. First, check this:
http://docs.oracle.com/javase/6/docs/jre/api/management/extension/com/sun/management/ThreadMXBean.html#getThreadAllocatedBytes%28long%29
All threads share all objects so none owns an object.
What you can do is use a memory profiler e.g. VisualVM which is free with the JDK, and have a look at how much each class is using (deep size, not shallow size) and this will tell you what you want to know.
I don't think that is possible, cause all thread share same memory heap. Thread is a running entity, but not data owner.

Are memory leaks totally absent in Java applications? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Creating a memory leak with Java
There is a "Garbage Collector" in Java, but does this mean that memory leaks are totally absent in a Java applications? If not, how and why do they happen?
I am more interested in scenarios in applications using JavaSE.
No - memory leaks can still exists in Java. They are just of a "different kind".
Wiki: Memory Leak
A memory leak, in computer science (or leakage, in this context), occurs when a computer program consumes memory but is unable to release it [the memory] back to the operating system.
In the case of Java it (normally) is when an unused/unneeded object is never made eligible for reclamation. For instance, an object may be stashed in a global List and never removed even if the object is never accessed later. In this case the JVM won't release the object/memory - it can't - because the object might be needed later, even if it never is.
(As an aside, some objects, such as directly allocated ByteBuffers also consume "out of JVM heap" memory which might not be reclaimed in a timely manner due to the nature of finalizers and memory pressure.)
In the case of Java, a "memory leak" is a semantic issue and not so much an issue of "not being able to release under any circumstances". Of course, with buggy JNI/JNA code, all bets are off ;-)
Happy coding.
Depends on how you define memory leak.
If you specifically mean having allocated memory that is no longer referenced by some memory root, then no, the garbage collector will eventually clean all of those up.
If you mean generally having your memory footprint grow without bound, that is easily possible. Just have some collection referenced by a static field and constantly added to.
Memory leaks in java are very possible. Here is a good article which has an example using core java. Fundamentally, a memory leak happens in java when the garbage collector cannot reclaim an object because the application holds a reference to it that it won't release, even though the object itself might no longer be used. The easiest way to create a memory leak in java is to have your application hold a reference to something, but not using it.
In the example, the unused object is a static List, and adding things to that list will eventually cause the JVM to run out of memory. Static collections are a pretty common source of "leaks", as they are typically long lived and mutable.
There are a few good responses so far. I don't want to recreate those posts, so I'll just add that one thing most people don't think about in connection with this subject is leaks in native code running via JNI. Native code running via JNI uses the JVM's heap space to allocate memory. So, if your application uses native code running via JNI that has a leak, your application has a leak.
Any object that has one or more live references to it will not be garbage-collected. So as long as some variable (either static, in the heap, or in the stack) refers to an object, that object will continue to occupy non-reclaimable memory space.
Unclosed resources (like sockets, JDBC connections, etc.) and constantly growing static collections are some of the better-known leak producers.

JVM with no garbage collection

I've read in many threads that it is impossible to turn off garbage collection on Sun's JVM. However, for the purpose of our research project we need this feature. Can anybody recommend a JVM implementation which does not have garbage collection or which allows turning it off? Thank you.
I wanted to find a fast way to keep all objects in memory for a simple initial proof of concept.
The simple way to do this is to run the JVM with a heap that is so large that the GC never needs to run. Set the -Xmx and -Xms options to a large value, and turn on GC logging to confirm that the GC doesn't run for the duration of your test.
This will be quicker and more straightforward than modifying the JVM.
(In hindsight, this may not work. I vaguely recall seeing evidence that implied that the JVM does not always respect the -Xms setting, especially if it was really big. Still, this approach is worth trying before trying some much more difficult approach ... like modifying the JVM.)
Also, this whole thing strikes me as unnecessary (even counter-productive) for what you are actually trying to achieve. The GC won't throw away objects unless they are garbage. And if they are garbage, you won't be able to use them. And the performance of a system with GC disabled / negated is not going to indicative of how a real application will perform.
UPDATE - From Java 11 onwards, you have the much simpler option of using the Epsilon (no-op) garbage collector; see
JEP 318: Epsilon: A No-Op Garbage Collector (Experimental)
You add the following options when you launch the JVM:
-XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC
When the heap is filled, no attempt is made to collect garbage. Instead, the Epsilon GC terminates the JVM.
Depending on your needs this could perhaps work:
Using the -Xbootclasspath option you may specify your own implementation of API classes. You could then for instance override the implementation of Object, and add to the constructor, a globalList.add(this) to prevent the objects from being garbage collected. It's a hack for sure, but for simple case-study it's perhaps sufficient.
Another option is to take an open source jvm and comment out the parts that initiate garbage collection. I would guess it is not that complicated.
Sun's JVM has no such option. AFAIK, no other JVM has this option either.
You did not state what it is that you are exactly trying to achieve but you have one of two options: either use a profiler and see exactly what the GC is doing, that way you can take its effects into consideration. The other is to compile one of the JVMs from source, and disable GC from there.
You can only turn off the GC if its not actually needed (otherwise your application would run out of memory) and if you didn't need to GC, it shouldn't run anyway.
The simplest option would be to not discard any objects, this will avoid GC being performed (And set the max memory very high so you don't run out).
You may find that you get GCs on startup and you may consider a no-GC when running acceptable.
the question is old but for those who might be interested, there is a proposal to
Develop a GC that only handles memory allocation, but does not implement any actual memory reclamation mechanism. Once available Java heap is exhausted, perform the orderly JVM shutdown.
JEP draft: Epsilon GC: The Arbitrarily Low Overhead Garbage (Non-)Collector
Maybe you could try making your VM's available memory sufficient for GC never to be run.
My (allbeit limited) experience leads me to suggest that the VM is, by default, extremely lazy and extremely reluctant to run GC.
giving -Xmx 16384M (or some such) and making sure that your research subject stays well below that limit, might give you the environment you wish to obtain, allthough even then it will obviously not be guaranteed.
There actually exists a dirty hack to temporarily pause GC. First create a dummy array in Java. Then, in JNI, use GetPrimitiveArrayCritical function to get hold of the pointer to the array. The Sun JVM will disable GC to ensure that the array is never moved and the pointer stays valid. To re-enable GC, you can call the ReleasePrimitiveArrayCritical function on the pointer. But this is very implementation specific since other VM impl may pin the object instead of disabling GC entirely. (Tested to work on Oracle Jdk 7 & 8)
Take a look at Oracle's JRockit JVM. I've seen very good near-deterministic performance on Intel hardware with this JVM and you can prod and poke the runtime using the Mission Control utility to see how well it's performing.
Though you can't turn GC off completely, I believe that you can use the -Xnoclassgc option to disable the collection of classes. The GC can be tuned to minimize latency at the expense of leaving memory consumption to grow. You may need a license to drop the latency as low as you need if you're going this route.
There is also a Realtime version of the JRockit JVM available but I don't think that there is a free-to-developers version of this available.
Can you get an open source JVM and disable its GC, for example Sun's Hotspot?
If there was no Garbage Collection what would you expect to be the semantics of code like this?
public myClass {
public void aMethod() {
String text = new String("xyz");
}
}
In the absence of GC any item newed and with a stack scoped reference could never be reclaimed. Even if your own classes could decide not to use local variables like this, or to use only primitive types I don't see how you would safely use any standard Java library.
I'd be interested to hear more about your usage scenario.
If I had this problem I would get IBM's Jikes Research Virtual Machine because:
The run-time system is written in Java itself (with special extensions)
The whole thing was designed as a research vehicle and is relatively easy to tweak.
You can't turn off GC forever, because Java programs do allocate and eventually you'll run out of memory, but it's quite possible that you can delay GC for the duration of your experiment by telling the JVM not to start collecting until the heap gets really big. (That trick might work on other JVMs as well, but I wouldn't know where to find the knobs to start twirling.)

Java without gc - io

I would like to run a Java program with garbage collection switched off. Managing memory in my own code is not so difficult.
However the program needs quite a lot of I/O.
Is there any way (short of using JNI for all I/O operations) that I could achieve this using pure Java?
Thanks
Daniel
What you are trying to achieve is frequently done in investment banking to develop low-latency real-time systems.
To avoid GC you simply need to make sure not to allocate memory after the startup and warm-up phase of your application.
As you seem to have noticed Java NIO internally does unwanted memory allocation.
Unfortunately, you have no choice but write JNI replacements for the problematic calls.
You need at least to write a replacement for the NIO Selector.
You will have to avoid using most of the Java libraries due to similar unwanted memory allocations.
For example you will have to avoid using immutable object like String, avoid Boxing, re-implement Collections that preallocate enough entries for the whole lifetime of your program.
Writing Java code this way is not easy, but certainly possible.
I am developing a platform to do just so.
Managing memory in my own code is not
so difficult.
It's not difficult - It's impossible. For example:
public void foo() {
Object o = new Object();
// free(o); // Doh! No "free" keyword in Java.
}
Without the aid of the garbage collector how can the memory consumed by o be reclaimed?
I'm assuming from your question that you might want to avoid the sporadic pauses caused by garbage collection due to the high level of I/O being performed by your app. If this is the case there are techniques for minimising the number of objects created (e.g. re-using objects from a pool). You could also consider enabling the Concurrent Mark Sweep Collector.
The concurrent mark sweep collector,
also known as the concurrent collector
or CMS, is targeted at applications
that are sensitive to garbage
collection pauses.
It's very hard (but not impossible) to disable GC in a JVM.
Look at the JNI "critical" functions for hints.
You can also essentially ensure you don't GC by not allocating any more objects (write a JVMTI agent that slaps you if you do, and instrument your code).
Finally, you can force a fatal OutOfMemoryError by ensuring that every object you allocate is never freed, thus when you hit -Xmx memory used, you'll fall over as GC won't be able to reclaim anything (mind you, you'll GC one or more times at this point before you fall over in a heap).
The real question is why you'd want to? What upside do you see in doing it? Is it for realtime? If so, I'd consider looking at one of the several realtime JVMs available on the market (Oracle, IBM, & others all sell them). I can't honestly think of another reason to do this while still using Java.
The only way you are going to be able to turn off garbage collection is to modify the JVM. This is should be feasible with OpenJDK 6 codebase.
However, the what you will get at the end is a JVM that leaks memory like crazy, with no reasonable hope of fixing the leaks. The Java class library APIs are designed and implemented on the assumption that there is a GC taking care of memory management. This is so fundamental that any serious attempt to "fix" it would lead to a language / library that is not recognizable as Java.
If you want a non-garbage collected language, use C or C++.
Modern JVM's are so good at handling short-lived objects that any scheme you devise on your own will be slower.
This is because the objects you handle yourself will become long-lived and receive extra deluxe treatment from the JVM in terms of being moved around etc. Of course, this is by the garbage collector, which you want to turn off, but you can do very little without any gc.
So, before you start considering what optimization to use, then establish a baseline where you have a large unoptimized, program and profile it. Then do your tweaks, and see if it helps, but you will never know if you do not have a baseline.
As other people have mentioned you can't disable the GC. However, you can choose to use the experimental 'Epsilon' garbage collector which will never actually perform any garbage collections. Warning: it will crash if your JVM runs out of memory (because it's not doing any garbage collections).
There's more info (including the command-line switch to use) at:
http://openjdk.java.net/jeps/318
Good luck!
GarbageCollection is automated memory management in java.So you can not disable GC
Since you say, "its all about predictability not straight line speed," you should look at using a realtime Java system with deterministic garbage collection.

Categories