When to use @Volatile

There are still some scenarios in which using volatile variables can help us write better code. These scenarios are based on two premises, both of which need to be true – if either of them is false then a different solution needs to be implemented:

  • A change in the value of the variable doesn't depend on its current state
  • The volatile variable doesn't depend on any other variables and other variables don't depend on it

The first premise helps to rule out scenarios like the thread-safe counter: because the change in the state is not atomic, future values can't safely depend on the current one.

The second premise, on the other hand, helps us to avoid the creation of inconsistent states because of dependencies from or to volatile variables. This example will not be safe because the second premise is not being followed:

class Something {

@Volatile
private var type = 0
private var title = ""

fun setTitle(newTitle: String) {
when(type) {
0 -> title = newTitle
else -> throw Exception("Invalid State")
}
}
}

In this case, trying to set title should throw an exception if type—which is volatile—is different from zero. The problem here is that type can be zero when a thread enters the when clause, but a different thread can set it to something different by the time title is modified. If that happens, then we will have an inconsistent state in which type is not zero, yet a title was set.

On the other hand, if both premises mentioned before are followed, we can proceed with using volatile variables. A common example of using them is to contain flags. Consider the following class:

class DataProcessor {

@Volatile
private var shutdownRequested = false

fun shutdown() {
shutdownRequested = true
}

fun process() {
while (!shutdownRequested) {
// process away
}
}
}

In this example both premises are valid:

  • The modification of shutdownRequested made in shutdown() doesn't depend on the current state of the variable itself –  it's always set to true
  • No other variable depends on shutdownRequested, and it doesn't depend on any other variable either

The advantage of this approach is that it allows any thread to request shutdown and it will be visible for all the threads immediately.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.97.53