#Need help using monitors to synchronize Reader-Writers problem with a Modifier,
1 messages · Page 1 of 1 (latest)
While you are waiting for getting help, here are some tips to improve your experience:
If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.
Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.
package textEditors.model;
import textEditors.main.Controller;
public class SharedBuffer {
private int bufferSize;
private Controller controller;
private String[] buffer;
private BufferStatus[] status;
private int writePos;
private int readPos;
private int modifyPos;
public SharedBuffer(int bufferSize, Controller controller) {
this.bufferSize = bufferSize;
this.controller = controller;
buffer = new String[bufferSize];
status = new BufferStatus[bufferSize];
writePos = 0;
readPos = 0;
modifyPos = 0;
for (int i = 0; i < bufferSize; i++) {
buffer[i] = "";
status[i] = BufferStatus.Empty;
}
}
public void writeData(String line, String threadName) {
synchronized (this) {
while (status[writePos]!=BufferStatus.Empty) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
buffer[writePos] = line;
status[writePos] = BufferStatus.New;
System.out.println(threadName + " - has written \"" + line + "\", position " + writePos);
String logEntry = threadName + " - has written \"" + line + "\", position " + writePos;
controller.logbookStatus(logEntry);
writePos = (writePos + 1) % bufferSize;
notifyAll();
}
}
public void modifyData(String find, String replace, String threadName) {
synchronized (this) {
while (status[modifyPos] != BufferStatus.New) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (buffer[modifyPos].contains(find)) {
buffer[modifyPos] = buffer[modifyPos].replace(find, replace);
System.out.println(threadName + " - has modified " + find + " to " + replace + " at position " + modifyPos);
String logEntry = threadName + " - has modified " + find + " to " + replace + " at position " + modifyPos;
controller.logbookStatus(logEntry);
}
status[modifyPos] = BufferStatus.Checked;
modifyPos = (modifyPos + 1) % bufferSize;
notifyAll();
}
}
public String readData(String threadName) {
String line = "";
synchronized (this) {
while (status[readPos] != BufferStatus.Checked) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
line = buffer[readPos];
status[readPos] = BufferStatus.Empty;
System.out.println(threadName + " - has read " + line + " position " + readPos);
String logEntry = threadName + " - has read, position " + readPos;
readPos = (readPos + 1) % bufferSize;
notifyAll();
return line;
}
}
public enum BufferStatus
{
Empty,
Checked,
New
}
}