Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
}
like image 250
Pedro Avatar asked Jul 08 '26 01:07

Pedro


1 Answers

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

like image 71
Saurabh Avatar answered Jul 10 '26 15:07

Saurabh