在写入管道尺寸小的物体时,管道传输块

时间:2010-03-12 16:01:46

标签: java serialization stream pipe apache-mina

我正在测试一个例子,我遇到了一些问题。出于某种原因,执行时在oos.writeObject(new SimpleObject());写入时阻塞,尽管管道应该传输数据,甚至(我假设)如果由于管道尺寸小而必须在较小的操作中执行。无论如何,当管道大小大于对象时,示例成功,而当管道大小小于对象时,示例失败。如果有人能够对此有所了解,那就非常感激了。

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.nio.ByteBuffer;

import org.apache.mina.filter.codec.serialization.ObjectSerializationInputStream;
import org.apache.mina.filter.codec.serialization.ObjectSerializationOutputStream;

public class ObjTest4 {
 public static void main(String[] args) {
  System.out.println("exec1");
  int objectsToSend = 10;
  int objectsRecvd = 0;

  try {
   System.out.println("exec2");

   PipedOutputStream pos = new PipedOutputStream();
   ObjectSerializationOutputStream oos = new ObjectSerializationOutputStream(pos);

   PipedInputStream pis = new PipedInputStream(pos, 500);
   ObjectSerializationInputStream ois = new ObjectSerializationInputStream(pis);

   oos.setMaxObjectSize(2000);
   ois.setMaxObjectSize(2000);

   while (objectsRecvd < objectsToSend) {
    System.out.println("exec3");

    oos.writeObject(new SimpleObject());

    System.out.println("exec3.1");

    oos.flush();

    System.out.println("exec3.2");

    System.out.println("oisavail: " + ois.available());

    Object o = ois.readObject();
    if (o != null) {
     objectsRecvd++;
     System.out.println("o: " + o);
    } else {
     System.out.println("recvd null");
    }
   }
  } catch (IOException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
 }
}

和被序列化对象的类:

package objtest;

import java.io.Serializable;
import java.util.EnumSet;

public class SimpleObject implements Serializable {
 /**
  * 
  */
 private static final long serialVersionUID = 1L;

 public String moo = "moo";
 public EnumSet<EnumTest> set = EnumSet.of(EnumTest.Test);
 public String moo2 = "moo2";
 public String moo3 = "moo3";
 public String moo4 = "moo4_";

 {
  for (int i = 0; i < 8; i++) {
   moo4 += moo4;
  }
 }

 /**
  * 
  */
 public SimpleObject() {
 // TODO Auto-generated constructor stub
 }

 /**
  * @return the moo
  */
 public String getMoo() {
  return moo;
 }

 /**
  * @param moo the moo to set
  */
 public void setMoo(String moo) {
  this.moo = moo;
 }
}

干杯,
克里斯

1 个答案:

答案 0 :(得分:0)

抱歉,我发现了问题--Java文档说not to use piped streams from a single thread, as it may deadlock the thread

  

尝试使用来自的两个对象   不推荐单线程,如   它可能使线程陷入僵局。