Skip to content

Instantly share code, notes, and snippets.

@rodel77
Last active November 24, 2018 20:46
Show Gist options
  • Save rodel77/b23f9ac07ec773dcb88fc2bd2dace308 to your computer and use it in GitHub Desktop.
Save rodel77/b23f9ac07ec773dcb88fc2bd2dace308 to your computer and use it in GitHub Desktop.
A guide to myself to understand Java Synchronization
Without Modifiers:
Instance methods are async, this means that you can call a method in the same object from different threads at the same time and they will be executed as well *at the same time*, without locking
Synchronized Method:
Synchronized Methods of the *SAME INSTANCE* can't be in execution at the same time, even if they are different methods.
Synchronized Blocks:
2 or more synchronized blocks with the same reference (the argument) can't be in execution at the same time.
Doing a synchronized block with the instance (this) as reference has the same behaviour as a Synchronized Method but with no need of making the entire method synchronized.
In order to add "global synchronization" on a block, you can set the class of the instance or any other static object as reference.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment