java memory allocation for local variables

独自空忆成欢 提交于 2019-12-24 22:08:46

问题


I have a java application which uses a SerialPortEvent which will be called continously ,

public void serialEvent(SerialPortEvent evt) {

    if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
        try {
            StringBuilder sBuilder = new StringBuilder();
            int length = input.available();
            byte[] array = new byte[length];
            int numBytes = input.read(array);
.......
......
}

i print the array variable contents in a text pane. I have a scenario in which the event will be called continuosly , it makes the the windows Memory(private Working set) increase gradually and doesn't stop.

My question is, whether creating new variables every time the event is called makes use of memory??

i simply get contents and print it in JTextpane and nothing else.


回答1:


Creating variables as such doesn't create a memory leak. The leak happens when you keep a reference to a local variable somewhere.

My guess is that you eventually append the content of sBuilder to the JTextpane which of course keeps the content around permanently.

The solution is to check the length of the JTextpane (number of lines). If there are too many, then remove some. That way, you always keep, say, 1000 lines in memory and the consumption will be in check.

Related:

  • Java Garbage Collection Basics
  • Quick introduction to Java Garbage Collector (JVM GC)
  • How Garbage Collection works in Java



回答2:


Of course creating new variables will increase the memory used by your program BUT unless you are keeping strong references to them (hard to tell by just reading the few lines of code you posted) this memory should be released at the next garbage collecting cycle. Now, I'm not a java guru, and I do not know how JTextPane works under the hood but if it keeps the whole string in memory while displaying it (most probably) I would expect the memory necessary for that string to continuously increase each time I add content to it. But if the increase you are seeing is significantly more than the amount of bytes you write in the text pane, I would look around for strong references that are kept around (or circular references). Mind that you can always hint the garbage collector to run by calling System.gc() but this is just a hint to the collector and it is up to it, whether to run or not.



来源:https://stackoverflow.com/questions/23753342/java-memory-allocation-for-local-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!