11

I have a java application that uses a lot of memory when used, but when the program is not being used, the memory usage doesnt go down.

Is there a way to force Java to release this memory? Because this memory is not needed at that time, I can understand to reserve a small amount of memory, but Java just reserves all the memory it ever uses. It also reuses this memory later but there must be a way to force Java to release it when its not needed.

System.gc is not working.

gren
  • 111
  • 1
  • 4

5 Answers5

7

As pointed out in the comments, it's not certain that, while the garbage collector disposes objects, it gives back memory to the system.

Perhaps Tuning Garbage Collection Outline provides the solution to your problem:

By default the JVM grows or shrinks the heap at each GC to keep the ratio of free space to live objects at each collection within a specified range.

  • -XX:MinHeapFreeRatio - when the percentage of free space in a generation falls below this value the generation will be expanded to meet this percentage. Default is 40
  • -XX:MaxHeapFreeRatio - when the percentage of free space in a generation exceeded this value the generation will shrink to meet this value. Default is 70

Otherwise, if you suspect that you're leaking references you can figure out how, what and where objects are leaked is to monitor the heap in JVisualVM (a tool bundled with the standard SDK). You can, through this program, perform a heap-dump and get a histogram over object memory consumption:

enter image description here

aioobe
  • 413,195
  • 112
  • 811
  • 826
2

What memory do you mean? If it is RAM (as opposed to the amount of used heap space of the Java VM itself) then this might be normal. It is a relatively expensive operation to allocate memory so once the JVM got some it is quite reluctant to give it back even if it is not needed at the time.

musiKk
  • 14,751
  • 4
  • 55
  • 82
1

Have you considered using a memory profiler? If you don't have access to one, you can start with capturing a bunch of jmap -histo <pid> and writing a script to figure the differences.

ddimitrov
  • 3,293
  • 3
  • 31
  • 46
0

System.gc has no guarantees about if it should free any memory when ran. See Why is it bad practice to call System.gc()?

Try tweaking the Xmx JVM arg down if it is set to a large value and take a look in JConsole to see what's going on with memory usage and GC activity. Normally you'd see a saw tooth pattern.

You might also want to use a profiler to see where the memory is being used and to identify any leaks.

Community
  • 1
  • 1
pjp
  • 17,039
  • 6
  • 33
  • 58
0

One of two things is happening:

1) Your application is leaking references. Are you sure that you aren't hanging on to objects when you'll no longer need them? If you do, Java must maintain them in memory.

2) Java's working just fine. You get no benefit from memory that you aren't using.

Greg D
  • 43,259
  • 14
  • 84
  • 117