Are threadlocal and volatile conceptually opposite of each other Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Are threadlocal and volatile conceptually opposite of each other without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Is it safe to say that a ThreadLocal variable is conceptually the ‘opposite’ of a volatile variable in Java?
Because in the former, every thread will only read/updatea local copy of the variable. But in the latter, every thread will always see the latest value of the variable that is in main memory….no chance of seeing stale values.

Answer

Exactly but with a slight twist,

  • a ThreadLocal variable is a variable different for each thread
  • any other variable exists only once so common for each Thread using the same object, whether it is volatile or not.

Volatile however specifies some kind of thread read/write boundary so they must synchronize on the latest value written by any other thread. However using volatile does not ensure thread safety.

E.g. a increment method incrementing a volatile int might still generate duplicates. To be sure that works thread safe you must synchronize the method updating the volatile attributes!

check this for more detailed information: https://www.cs.umd.edu/users/pugh/java/memoryModel/jsr-133-faq.html

We are here to answer your question about Are threadlocal and volatile conceptually opposite of each other - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji