wood burning stoves 2.0*
The moose likes Threads and Synchronization and the fly likes What is synchronized ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "What is synchronized ?" Watch "What is synchronized ?" New topic
Author

What is synchronized ?

Shahir Deo
Ranch Hand

Joined: Mar 19, 2013
Posts: 80

Hi Guys, Can anybody explain me what is synchronized keyword and how to use in a running thread?
explain me with an example.
thanks.,


Knowledge enlivens the soul.
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

Have you read this part of the Java Tutorials? It explains what synchronization does and why you need it, with examples.


Steve
Shahir Deo
Ranch Hand

Joined: Mar 19, 2013
Posts: 80

Steve Luke wrote:Have you read this part of the Java Tutorials? It explains what synchronization does and why you need it, with examples.


Steve , When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block until the first thread is done with the object.

we can do this by wait() , join() , yield() isn't it?
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

Usman Shahir wrote:Steve , When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block until the first thread is done with the object.

we can do this by wait() , join() , yield() isn't it?

No. wait() will wait for a signal, not an open lock, and must be in a synchronized block. join() waits for a thread to complete, which is far different than waiting for a block of code to complete. And yield() offers up some of the current Thread's processor time if other Threads need to use it. These are all different than what synchronized blocks are for.

The fact that synchronization makes you wait on the lock is almost a necessary side effect. You don't use it because you want threads to block, you accept that other threads will block to protect the data the code is using.
 
jQuery in Action, 2nd edition
 
subject: What is synchronized ?