Multithreading synchronization between reading and writing in a channel I was hoping to get some feedback on what the recommended design pattern are for this subject.

public class Channel {

    private AtomicInteger buffer = new AtomicInteger(0);

    public void read() {
        // This function should keep blocking until there is something to read.

        while (buffer.get() == 0) {
            // Maybe a sleep? (Although NetBeans gives a warning for a sleep in a loop)
        }

        buffer.decrementAndGet();
    }

    public void write() {
        // This function should just write (nothing) to the buffer (by increasing the counter of the imaginary buffer).
        buffer.incrementAndGet();
    }
}


Is this safe for use in multithreading? Or is there a better approach?
if multiple threads try to read they may each decrement the buffer if one thread was interrupted right before it could decrement and after it passed the while

Instead use a Semaphore which is designed for just this:

public class Channel {

    private Semaphore sem = new Semaphore(0);

    public void read() throws InterruptedException {
        // This function should keep blocking until there is something to read.

        sem.acquire();
    }

    public void write() {
        // This function should just write (nothing) to the buffer (by increasing the counter of the imaginary buffer).
        sem.release();
    }
}


otherwise you should decrement in a loop:

int read;
do{
    while((read = buffer.get())==0){
    //sleep
    }
}while(!buffer.compareAndSet(read, read-1));