I was reading about synchronized methods/statements in the Java tutorial here: https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html
It made sense, but once I started coding I came across a dilemma: What do I do about the object's access to its own fields?
Consider this example:
public class MyClass extends Thread {
private PrintWriter printWriter;
public synchronized void setPrintWriter(PrintWriter pw){
printWriter = pw;
}
public synchronized PrintWriter getPrintWriter(){
return printWriter;
}
@Override
public void run() {
PrintWriter pw = getPrintWriter();
while (!this.isInterrupted()) {
try {
pw.println("some stuff");
pw.flush();
Thread.sleep(1000);
}
catch (InterruptedException e){
//pass the interrupt along (will terminate the loop)
Thread.currentThread().interrupt();
}
}
//finish by printing this when we've received an interrupt
pw.println("some more stuff");
}
}
This will work, but it seems a little ridiculous to use a getter to get a copy pw
, when I can just use printWriter
directly. But I'm not sure if it's necessary in this case, or in some other case similar to this. Maybe it protects me from corruption if some other thread called setPrintWriter at the same time that I was using printWriter?