readObject()阻塞特定对象

时间:2012-05-11 09:24:31

标签: java serialization

我正在编写服务器/客户端程序。客户端将“请求”(这是为此目的设计的对象)发送到服务器,服务器使用ObjectInputStream对它们进行解码。所有“请求”对象都属于同一类,只是数据字段不同。
一切都通常有效;但是在某些特定的状态下(可能当Request对象有点大,但不超过200 kb!)服务器端的readObject()只是阻塞而没有异常。
有什么想法吗?!

服务器代码:

public class ConnectionThread extends Thread {

    Socket con;
    Request request;

    public ConnectionThread(Socket s) {
        con = s;
        try {
            ObjectInputStream in = new ObjectInputStream(con.getInputStream());
            // Works till here; the object "in" is initialized.
            request = (Request) in.readObject();
            // This line is not reached, in particular cases.
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ConnectionThread.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ConnectionThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

...
}

客户端代码:

public static void saveStoreDataForTable(DataTable tb) {
    try {
        Socket s = new Socket("localhost", portNo);
        ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
        out.writeObject(new Request("saveStoreData", 
                new Object[] 
                {tb.getEdited(), tb.getRemoved(), tb.getNewTables(), tb.getAlterations()}));
        out.flush();
        // These lines work. But I can't get servers respone; again, in some particular cases.
...
}

1 个答案:

答案 0 :(得分:1)

您应该将I / O从构造函数移动到start()方法。目前你正在构造这个线程的线程中进行I / O,这几乎是一个错误的线程。