局部变量的Java内存分配 [英] java memory allocation for local variables

查看:188
本文介绍了局部变量的Java内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 SerialPortEvent 的Java应用程序,该应用程序将被连续调用,

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);
.......
......
}

我在文本窗格中打印 array 变量内容. 我有一种情况,该事件将被连续调用,这会使Windows的Memory(私有工作集)窗口逐渐增加并且不会停止.

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??

我只是获取内容并将其打印在JTextpane中,仅此而已.

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.

我的猜测是,您最终会将sBuilder的内容附加到JTextpane上,这当然会永久保留内容.

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

解决方案是检查JTextpane的长度(行数).如果太多,请删除一些.这样,您总是可以保留1000行内存,而消耗量将得到控制.

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.

相关:

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

这篇关于局部变量的Java内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆