1

A Buffer class has methods write and read. The buffer is used by multiple threads. Threads producing data use the write method to write a data value to the buffer; threads consuming data call the read method to get the next data value from the buffer. The following code, which works when there is only a single thread, but the methods read and write are not correct when multiple threads are used.

Describe 4 changes that are needed to correct the code of the two methods, explaining the effect of each change. (You may write out the corrected code if you wish, but this is not required.)

public class Buffer<E> {

    private int maxSize ; // the maximum length of the buffer
    private List<E> entries ; // the entries in the buffer

    // constructor
    public Buffer(int maxSize) {
        entries = new ArrayList();
        this.maxSize = maxSize;
    }

    public void write(E entry) {
        entries.add(entry);
    }

    public E read() {
        return entries.remove(0);
    }

}

My Attempt

One change would be that we need synchronization to avoid multiple threads reading/writing at the same time, but I'm not sure on what other changes I could make

Chris Mantle
  • 6,595
  • 3
  • 34
  • 48
Prash
  • 150
  • 9

1 Answers1

-1

best to use concurrent queue instead

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

public class Buffer {
    private int maxSize; // the maximum length of the buffer
    public Queue<String> entries = new ConcurrentLinkedQueue<String>();
    private static Buffer instance;

    // constructor
    public static Buffer getInstance() {
        return instance = new Buffer();
    }

    public void write(String entry) {
        entries.add(entry);
    }

    public synchronized String read() {
        return entries.poll();
    }
}
Bhavesh
  • 889
  • 1
  • 10
  • 16