问题
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