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

How to connect to a remote database using Applet?

0 Answers  


Can an unreachable object become reachable again?

3 Answers  


What is Connection pooling? Explain Pros and Cons?

1 Answers  


When a thread is executing a synchronized method , then is it possible for the same thread to access other synchronized methods of an object ?

0 Answers  


Explain about field hiding in java?

0 Answers  


How to compare two strings in java program?

0 Answers  


List java api that supports threads?

1 Answers  


How do you check if a string is lexicographically in java?

0 Answers  


My interview asked what is dynamic variable in java and where we use them.

2 Answers   IBM,


Is void a keyword in java?

0 Answers  


Is singleton class thread safe?

0 Answers  


Suppose there is an array list [10,5,20,19,15,24].Print them in ascending & descending order in collection framework concept ???

2 Answers   Cognizant,


Categories