How does synchronized modifier work?



How does synchronized modifier work?..

Answer / 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

More Core Java Interview Questions

Is delete, next, main, exit or null keyword in java?

1 Answers  


Explain in detail about encapsulation with an example?

4 Answers  


What is singleton service?

0 Answers  


Why map is used in java?

0 Answers  


what is overloading and overriding with example?

2 Answers   CMC,






What are the ways to instantiate the class class?

0 Answers  


Is zero a natural number?

0 Answers  


Write a program that takes a 5 digit number and calculates 2 power that number and prints it.

1 Answers  


What is the meaning of variable in research?

0 Answers  


What is the differnence between String Buffer and String builder despite having knowledge that String builder is faster than String Buffer and last one is threadsafe.please tell another important difference.

3 Answers   IBM,


what happens when a thread cannot acquire a lock on an object? : Java thread

0 Answers  


How to make a method thread safe without using synchronized keyword?

8 Answers   Persistent, Societe Generale,


Categories