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