1

I have this statement in a while loop, I noticed that in the windows task manager, the memory used by the java app process is keep increasing, about several k per second. Is there a memory issue with String.format?

String str = String.format("%dDays %02d : %02d : %02d",days,hours,minutes,seconds);
jlordo
  • 37,490
  • 6
  • 58
  • 83
Dewitt
  • 177
  • 1
  • 9

3 Answers3

1

If you're not using str anywhere after then it's just that the garbage collector has not run so the memory that should be released hasn't been collected yet. This is probably because Java doesn't need it (since it has some reserve pages left) yet as Java has to use a certain amount of memory before it starts reclaiming memory since running the garbage collector is an expensive task.

Jesus Ramos
  • 22,940
  • 10
  • 58
  • 88
0

I'm going to assume that you do not keep references to the strings you create.

Basically, that call creates a new object every time it runs. Those objects remain in memory until the Java Virtual Machine decides to perform garbage collection. The JVM will not do so until it decides that it is necessary. Necessary is generally when your memory usage exceeds a certain threshold. That threshold will depend on your machine and the setting the JVM was started with.

Aurand
  • 5,487
  • 1
  • 25
  • 35
0

It should help if you do something like:

String days = "Monday";
String hours = "10:00pm";
String minutes = "60";
String seconds = "01";

while(condition){
     String str = String.format("%dDays %02d : %02d : %02d",days,hours,minutes,seconds);
}

This will pass the reference to the string instead of taking 32 bits up for each string of each iteration in your loop. If you can't help that your determine your strings in the loop try switching to character or bytes (if possible) that will reduce the amount of memory you use.

If you want to force the garbage collector to run (very unsafe) look here

http://stackoverflow.com/questions/1481178/forcing-garbage-collection-in-java
SpiffyDeveloper
  • 127
  • 1
  • 7