Alex Rivera | Logout

Is a Java socket's PrintWriter thread safe?

Asked 2009-04-03T14:53:27.043
10

So, I have two threads.

Thread one manages the client connections. (There is only one client and one server)
I call it my server thread.

Thread two manages sending messages to the client. I call it my message processor thread.

Thread one is responsible, among other things sending a heartbeat to the client periodically.

When programming I made an assumption that the sockets weren't thread safe, but the buffers were, and as long as I was using seperate buffers for the server and processor threads I would be fine.

I also made the assumption that the "PrintWriter" was analogous to the socket buffer in Java.

Under these assumptions I wrote this function to send a heartbeat:

public void sendHeartBeat(){
        logger.info("Sending a hearbeat!");
        PrintWriter printWriter=null;
        try {
            printWriter = new PrintWriter(clientSocket.getOutputStream());
        } catch (IOException e) {
            logger.info(e.toString());
        }
        if(printWriter!=null){
            printWriter.print("HEARTBEAT#");
            printWriter.flush();
        }
    }

The other thread, the "processor" one does something similar in that it does:

printWriter=new PrintWriter(theServer.getClientSocket().getOutputStream());

In this manner I would create a new "buffer" every time I wished to send a heartbeat, and my messages would never get overwritten.

Unfortuneately this does not seem to be the case. And I get an message coming through the pipe like this: dsgdsbHEARTBEAT#sdg

This causes a core dump later.

Here are my questions:

1) Sockets are obviously not thread safe, but are the PrintWriters I get from them thread safe? Or is it just returning the same PrintWriter?

2) What is analogous to the socket buffer in Java? How should I think about this problem?

3) How do I make it so that these

Edit
Report

1 Answer

5

You need a way to use the same PrintWriter between the threads (t1.writer == t2.writer, not just PrintWriters created from the same OutputStream). With the same PrintWriter, all writing operations are synchronized.

answered 2009-04-03T14:58:48.403

Your Answer