I have runnable which is downloading some file from internet, it looks as follows:
class Downloader implements Runnable {
volatile Status status;
public void run() {
// ...
while (status.isInProgress()) { ... }
}
}
Status looks as follows:
public enum Status {
PAUSED {
public int someData() { return 0; }
},
INPROGRESS {
public int someData() { return 1; }
}
public abstract int someData();
private String msg;
public String getSomeMsg() {
return msg;
}
public void setSomeMsg(String s) {
msg=s;
}
public boolean isInProgress() {
return this == INPROGRESS;
}
}
when user presses Pause button, status variable is set to PAUSED from GUI thread.
Code is compiled with java 1.6, and is compiled for Android platform.
My question is whether this is thread safe to set/read Enum like this? I have read great article in here:
http://javarevisited.blogspot.com/2011/06/volatile-keyword-java-example-tutorial.html
and I am quite convinced that it is save, but it does not say much about enums.
Accordingly with this page it is OK to use volatile
with both primitives and objects (with includes enumerations). Also, this is the typical use of volatile
keywork as you can see here.
NOTE: Assuming your loop will break when done (as you did not define a DONE enum value), the worst case would be when (i) the user pauses AND (ii) the download finishes before next iteration. In this case the user clicks pause, but sees a "download complete" message.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With