Hi,
Just need some discussion on general topic of memory leaks in java. I am not 100% sure how garbage collections works in java especially when we reassign strings to new values in a continuous loop because I believe strings are immutable! For example lets say in the following loop:
String buffer;
buffer= “”;
for (i=o; i<1000;i++) buffer+="some string ";
My understanding is that the variable buffer will be freed and recreated with new value in every iteration in the loop due to the immutable nature of strings in JAVA (same with JavaScript but that’s irrelevant for this discussion)! If the whole code is in a unending periodic timer loop (like for example say an Ignition client refreshing the values or screen every fixed interval of say once a second or a few second, will it cause memory leaks? Can I safely assume that the JVM’s garbage collector take care of garbage collection without causing any memory leaks?! In C or C++ I would have defined a large array for buffer (sufficient to to hold the largest buffer size i expect in any of the timer loops) and reused the array in every timer cycle. That way I use the max buffer size in every cycle but in each cycle I use different buffer size . There is no question of creating a new buffer every cycle and the resulting memory leaks.
Another example is let us say a method returns a list of items for a given list of items passed as input argument to it. I assign the returned list variable to a local list variable of same type. This method called in a never-ending timer loop every few seconds. I guess the local list variable will get freed and new list will be created automatically by the JVM? Or do I have to delete the list explicitly after its use is over in the code. Will the garbage collector take care of the memory management of freed list of variables. Do I need to take care of anything special to avoid memory leaks? This is especially important for Ignition type of systems which are continuously running applications triggered by timer loops unlike other OLTP applications which triggered by manual actions.
Any replies to these doubts will be appreciated. We need to be clear about these issue to design robust real time systems especially those developed in JAVA which is not designed with hard real time system in mind!
Best regards
PRAMANJ