Reputation: 4160
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
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
Reputation: 7964
It's a standard producer-consumer problem. JDK provides ArrayBlockingQueue to handle this in seamless manner.
Upvotes: 9