0

BACKGROUND

I recently wrote a java application that consumes a specified amount of MB. I am doing this purposefully to see how another Java application reacts to specific RAM loads (I am sure there are tools for this purpose, but this was the fastest). The memory consumer app is very simple. I enter the number of MB I want to consume and create a vector of that many bytes. I also have a reset button that removes the elements of the vector and prompts for a new number of bytes.

QUESTION

I noticed that the heap size of the java process never reduces once the vector is cleared. I tried clear(), but the heap remains the same size. It seems like the heap grows with the elements, but even though the elements are removed the size remains. Is there a way in java code to reduce heap size? Is there a detail about the java heap that I am missing? I feel like this is an important question because if I wanted to keep a low memory footprint in any java application, I would need a way to keep the heap size from growing or at least not large for long lengths of time.

user2899525
  • 93
  • 10
  • 1
    Have you looked at: http://stackoverflow.com/questions/4952568/is-there-a-way-to-lower-java-heap-when-not-in-use. There are some notes about java heap size control. – Mr Rho Jan 19 '16 at 19:37
  • The GC only runs when it needs to to save CPU consumption. If it was to run every time you released some memory, your application would be very slow. – Peter Lawrey Jan 19 '16 at 19:51
  • Makes sense....thanks for the suggestions! – user2899525 Jan 19 '16 at 21:13

2 Answers2

2

Try garbage collection by making call to System.gc()

This might help you - When does System.gc() do anything

Calling GC extensively is not recommended.

Community
  • 1
  • 1
Ravindra Gullapalli
  • 8,591
  • 3
  • 41
  • 66
0

You should provide max heap size with -Xmx option, and watch memory allocation by you app. Also use weak references for objects which have short time lifecycle and GC remove them automatically.

eg04lt3r
  • 2,269
  • 12
  • 19