Blog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2025 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Java
Javahard

`volatile` vs `synchronized` — what problem does each solve?

Tags
#concurrency#volatile#synchronized
Back to categoryPractice quiz

Answer

`volatile` guarantees visibility (and ordering) of a variable between threads, but doesn’t make compound operations atomic. `synchronized` provides mutual exclusion and also establishes happens-before (visibility) for the protected code.

class StopFlag {
  private volatile boolean stop = false;

  void requestStop() {
    stop = true;
  }

  void runLoop() {
    while (!stop) {
      // do work
    }
  }
}

Related questions

Java
HashMap vs ConcurrentHashMap: when should you use each?
#java#collections#concurrency
Java
`synchronized` vs `ReentrantLock`: what are the differences?
#java#concurrency#locks
Java
Parallel streams: when can they help and what are common pitfalls?
#java#streams#parallel
Java
`synchronized` vs `ReentrantLock` - when would you choose one?
#concurrency#locks#synchronized
Java
What does `ThreadLocal` do and what is a common pitfall?
#threadlocal#concurrency#thread-pool
Java
Java Memory Model: what does “happens-before” mean (in simple terms)?
#jmm#happens-before#concurrency