Rate This Document
Findability
Accuracy
Completeness
Readability

Synchronized Synchronization Lock

The synchronized keyword provides a built-in lock mechanism in the Java language to meet the requirements of Java atomicity and visibility. Each object has an associated monitor for mutually exclusive access. If two threads attempt to "synchronize" on the same object, one thread needs to wait for the synchronization of the other to complete.

  • Synchronization method

    The synchronized method is declared by adding the synchronized keyword to the method declaration. The following code indicates that only one thread can execute func() at a time and other threads must wait.

    public synchronized void func();
  • Synchronize code blocks.

    When concurrent threads access code blocks in an object, only one thread can execute the code block at a time. The other thread can execute the code block only after the current thread completes execution of the code block.

    synchronized(object) {//Code that can be accessed}