In Java, the synchronized keyword can be used as a method modifier orCodeBlock, for example:
Public synchronized void dosomething ()
Synchronized (semaphore ){
...
}
The Methods modifier has the following advantages:
- The synchronization policy is explicit and can be written to the API documentation.
- The method is relatively basic, thus reducing the opportunity of deadlock, although it is still easier to create
Disadvantages:
- Low method synchronization Performance
- Generally, developers do not have a clear and comprehensive lock policy when using the synchronized keyword, which leads to a lot of synchronization content.
The advantages of Synchronous Code blocks include:
- You can easily control the content to be locked.
- Better performance than method Synchronization
Disadvantages:
- It is easy to form nested synchronization code blocks, which may also cause deadlocks.
- The synchronization policy cannot be docized. You need to check the method code to understand it.
Http://codemonkeyism.com/java-interview-question-synchronized/.