简体   繁体   中英

java memory allocation for local variables

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.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM