Volatile keyword usage in java
- Manbodh ratre
- Dec 24, 2022
- 1 min read
if we are using any common resource in the different threads, then it can cause an error.
Suppose one flag is used by two thread, and one thread do the changes in shared variable, then the second thread may not read the updated value, it may run infinite times in the below example.

how thread read the values

Solution is very simple for this case
we just have to add a volatile keyword for a shared flag
volatile boolean flag = true;after this change, if any thread change the value of flag, then another thread can read the changes and the problem will be solved.








Comments