The following screenshot shows the output of the example:
The application doesn't finish its execution because the task thread has not finished. When we change the value of volatileFlag-as its flag attribute is marked as volatile--the new value is written in the main memory and VolatileTask accesses the value immediately and finishes its execution. On the contrary, when you change the value of the flag object--as its flag attribute is not marked as volatile-the new value is stored in the cache of the main thread and the task object doesn't see the new value and never ends its execution. The volatile keyword is important not ...