2

I have one thread, that is receiving tcp packets and add each line to a buffer that is an ArrayList<String>. The other thread should periodically check if new data is available, but only if the buffer is currently not locked. But how do I check if it has been locked? In C++ I could explicitly lock a mutex.

This is some pseudo code of what I'd like to do:

 while(buffer.isLocked()) 
 { 
    buffer.wait();
 }

 buffer.lock();
 buffer.add(tcpPacket);
 buffer.unlock();
 buffer.notify();

This is my java code so far:

void process(String tcpPacket)
{

     synchronized(buffer)
     {
         buffer.add(tcpPacket);
     }
     buffer.notify();
}

2 Answers 2

9

It's a standard producer-consumer problem. JDK provides ArrayBlockingQueue to handle this in seamless manner.

Sign up to request clarification or add additional context in comments.

Comments

0

Though in this case you could consider using a pipe. (PipedInputStream and PipedOutputStream) and then use blocking IO methods to ensure that threads properly wake up as and when packets arrive.... This seems a far simpler approach to the “shared buffer” problem.

3 Comments

That would block the producer when the pipe fills. These piped streams are far more trouble than they are worth.
True, though there is the question whether or not that is in fact desirable behaviour for IO operations? That is you don't want to overrun your consumer thread (unbounded queues will wind up consuming a lot of memory if the consumer can't keep up with the producer). At which point, blocking on the IO in the producer thread when the pipe fills is a good way to prevent memory usage from growing indefinitely and to ensure the consumer thread gets priority once the buffer fills up.
I would personally only have one thread and let TCP do the blocking of the sender actually. I can never understand the enthusiasm for these two-step designs. The reading process is the consumer and the writing process is the producer. No need to replicate that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.