What is the difference between `volatile` and `synchronized` in Java?
`volatile` guarantees thread safety, while `synchronized` only ensures atomicity.
Thatâ€™s partially correct. `volatile` ensures visibility, not thread safety in general. `synchronized` guarantees both atomicity and visibility for blocks of code.
Can you explain how `synchronized` ensures atomicity in a block of code?