Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getMethod is caching and cause a memory leak

I am using an automatic generated Java class for executing a special method. Because of this i have to invoke the method by reflection.

This execution is triggered by a Swing Thread, because the method (invoked from the "unknown" class) is updating a UI Element. Every execution of a new Thread is searching for a Method in the class by calling

Class {
...
public Method[] getMethods() throws SecurityException
...
}

The logic of getMethods, caches the element, but i do not know why. A Profiler shows me, that Method obejcts are floating the memory.

I can disable the method caching of Java by setting the system property "sun.reflect.noCaches", but my application became incredible slow, after i changed these property.

Question: I could implement my own caching algorithm, before i try to get the method from the class. But the project i am working is very big and we have multiple reflection calls.

What can solve these problem?

Which cirumstances can trigger these memory leak (wrong classloader,...)?

The project is running under Linux using Java 1.5

like image 551
Markus Lausberg Avatar asked Jun 22 '11 06:06

Markus Lausberg


People also ask

What are the causes of memory leaks?

Memory leak occurs when programmers create a memory in heap and forget to delete it. The consequences of memory leak is that it reduces the performance of the computer by reducing the amount of available memory.

What is the main cause of memory leaks in application in C?

Memory leaks occur when new memory is allocated dynamically and never deallocated. In C programs, new memory is allocated by the malloc or calloc functions, and deallocated by the free function.

Does unclosed streams cause memory leak in Java?

Through Unclosed Resources Whenever you create a new connection or open a stream, the JVM allocates memory for these resources. In such cases, if you forget to close these resources can block the memory, reduce performance, and may even result in OutOfMemoryError.

What is memory leak?

In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that memory which is no longer needed is not released.


1 Answers

  1. First thing, the cache that it uses is a SoftReference, so the cached methods will be removed before an OOME ever occurs.

  2. If you still want to remove it, just call the clearCachesOnClassRedefinition() method after every call to getMethods(..); you will have to use reflection as the method is private.

like image 112
Suraj Chandran Avatar answered Oct 12 '22 07:10

Suraj Chandran