Is the following code thread-safe? Do I really need to set dataReady to be volatile, though there is only one write and multiple reads from one thread (with while loop as shown below)?
public class MyApplication extends Application
{
/* a flag indicates if the data is fully retrieved from the database */
private volatile boolean dataReady = false;
@Override
public void onCreate()
{
super.onCreate();
new AsyncTask<Void, Void, Void>()
{
@Override
protected Void doInBackground(Void... params)
{
// retrieve data from the database
return null;
}
@Override
protected void onPostExecute(Void result)
{
dataReady = true;
}
}.execute();
}
public boolean isDataReady()
{
return dataReady;
}
}
On other thread (not the main thread):
while(!getApplication().isDataReady()); // wait until the data is ready
Marking the boolean as
volatileguarantees visibility, in other words it guarantees that all threads will see its current value. Since you are making writes and reads in different threads, you have to mark the boolean asvolatile.If you don’t mark it as
volatile, it is very possible (but not systematic) that your main thread will setdataReadyto true and the other thread will see the flag as false and continue looping. In a worse case scenario, it could even become an infinite loop.