Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of taking volatile variable in ThreadLocal instance

This is one of questions asked to me in one of the technical talks.

public class MyClass {

    volatile int i;
}

I am using the above MyClass as a ThreadLocal, so what is the use of taking any volatile variable inside this?

final ThreadLocal<MyClass> threadLocal = new ThreadLocal<MyClass>();
like image 662
Sunny Gupta Avatar asked May 02 '26 05:05

Sunny Gupta


1 Answers

If that instance is used exclusively with ThreadLocal and not passed around, there doesn't appear to be much point in volatile.

Note, however, that MyClass is just a class like any other: there's nothing preventing it from being used in contexts not involving thread-local storage. In those contexts it could well make sense for the variable to be volatile.

like image 61
NPE Avatar answered May 04 '26 17:05

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!