How does synchronized modifier work?

Answer Posted / javamasque

Synchronized is used to make a resource thread safe. If an object or resources is accessed by more than one thread, then these should be under synchronization. Only method and block can be synchronized.

Synchronized method
• As an instance method is synchronized then, the object is locked for a period of time as a thread is accessing the method.
• As a class method (static) is synchronized then, whole class is locked for a period of time as a thread is accessing the class method.

Synchronized block
• A particular set of statements (lines of codes) inside method or block is synchronized with synchronized block.
• An object reference is passed inside synchronized block to make a particular set of statements inside instance method or block.

synchronized (this){
}
• If a particular set of synchronized statements inside instance method or block is accessed by a thread then whole object is locked.
• A class reference is passed inside synchronized block to make a particular set of statements inside static method or block.

Synchronized (Class.class){
}

Is This Answer Correct ?    4 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What are the rules for variable declaration?

507


What are the advantages of autoboxing?

539


How do you avoid global variables?

544


What is the scope or life time of instance variables?

660


What is difference between module and function?

542






Can an integer be null java?

560


How do I get a substring?

529


Which is faster call by value or call by reference?

502


What is arrays aslist in java?

523


What do you understand by java virtual machine?

709


What is the purpose of garbage collection in java, and when is it used?

566


What is the public method modifier?

546


What does the string method compareto () do?

540


Why pointers are not used in java?

581


Can we override protected method in java?

582