Difference between Synchronized & Volatile in Java

volatile keyword in Java is field modifier while synchronized modifies code blocks and methods.

synchronized acquires and releases locks on entire code block or method while volatile keyword doesn’t require lock.

synchronized method/code block affects performance more than the volatile.

Since volatile keyword only synchronizes the value of one field between “main memory” and “thread memory” while synchronized synchronizes all variables into the code block or methods so it has more memory overhead then volatile.

You can not synchronize on the null object, However, volatile variable in Java can be null.

In an multi-threading environment, Threads may go in waiting mode for longer duration in case of synchronized used but that is not the case with volatile keyword.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.