Using volatile to secure overflow tape

I have a runnable that downloads a file from the Internet, it looks like this:

class Downloader implements Runnable { volatile Status status; public void run() { // ... while (status.isInProgress()) { ... } } } 

The status is 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 the user clicks the Pause button, the status variable is set to PAUSED from the GUI stream.

The code was compiled using java 1.6 and compiled for the Android platform.

My question is, is it thread safe for installing / reading Enum as follows? Here I read a wonderful article:

http://javarevisited.blogspot.com/2011/06/volatile-keyword-java-example-tutorial.html

and I am quite sure that it is preserved, but it says little about transfers.

+4
source share
2 answers

According to this page , you can use volatile with both primitives and objects (including enumerations). It is also a typical use of volatile keywork, as you can see here .

NOTE. Assuming your loop breaks when you finish (because you did not specify a DONE rename value), the worst case would be when (i) the user pauses AND (ii) the load finishes before the next iteration. In this case, the user pauses, but sees the message "Download complete."

+4
source

I assume that you have more than one thread that reads a value from "status". If so, then the “save” code like volaile ensures that your processor will always be the “new” value during processing (it cannot read it from the cache). But this will not impede any consensus changes or anything else, I will only assure that if some thread changes the value of another thread, it will change the value.

+1
source

Source: https://habr.com/ru/post/1437429/


All Articles