Pedro
Pedro

Reputation: 4160

Java: synchronized buffer

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();
}

Upvotes: 2

Views: 2479

Answers (2)

user268396
user268396

Reputation: 11986

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.

Upvotes: 0

Saurabh
Saurabh

Reputation: 7964

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

Upvotes: 9

Related Questions