JApplet在ObjectInputStream.readObject(未知来源)上获取java.lang.OutOfMemoryError异常

时间:2011-01-16 00:17:18

标签: java out-of-memory

我写了一个连接到服务器的JApplet。连接时,它会收到一个ImageIcon。收到后,它会向服务器发送字符串“I”以进行确认。这表示服务器发送下一个imageIcon。

    while(noExceptions){
   try{
    Object something = in.readObject();
    if(something instanceof ImageIcon){
     camDisplay.setIcon( (ImageIcon)something );
     validate();
     sendMessage("I");
    }else{
     System.out.println("What the hell was that?!");
    }
    Runtime rt = Runtime.getRuntime();
    rt.gc(); 
   }catch(Exception e){
    noExceptions=false;
    ...
   }
     }

当我第一次得到异常时,我将调用添加到了垃圾收集器,但它没有帮助。我放了一些printlns,它总是在第128张图像上崩溃。在Object something = in.readObject();抛出异常

camDisplay是一个显示在applet中的JLabel。

Exception in thread "Thread-12" java.lang.OutOfMemoryError: Java heap space
    at java.lang.reflect.Array.newArray(Native Method)
    at java.lang.reflect.Array.newInstance(Unknown Source)
    at java.io.ObjectInputStream.readArray(Unknown Source)
    at java.io.ObjectInputStream.readObject0(Unknown Source)
    at java.io.ObjectInputStream.readObject(Unknown Source)
    at javax.swing.ImageIcon.readObject(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
    at java.io.ObjectInputStream.readSerialData(Unknown Source)
    at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
    at java.io.ObjectInputStream.readObject0(Unknown Source)
    at java.io.ObjectInputStream.readObject(Unknown Source)
    at RoboClient.run(RoboClient.java:226)
    at java.lang.Thread.run(Unknown Source)

FIX:

System.out.println((sendImageCount++)+" send image");
        out.writeUnshared( new ImageIcon(_image) );
        out.flush();
        if(sendImageCount>100){
            out.reset();
            sendImageCount=0;
        }

2 个答案:

答案 0 :(得分:2)

请参阅ObjectOutputStream.reset()和ObjectOutputStream.writeUnshared()。

答案 1 :(得分:-1)

解决此问题的一种粗略方法是在检索每个x(在本例中为50)ImageIcons之后刷新输入流并关闭inputStream并重新打开以获取剩余的ImageIcons。现在GC将能够垃圾回收早期的图像。

看起来Inputstream保存了阻止Gced的ImageIcons的引用。