This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Synchronized with example Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Synchronized with example" Watch "Synchronized with example" New topic
Author

Synchronized with example

Rajendra Prakash
Ranch Hand

Joined: Sep 10, 2009
Posts: 293
Hi Friends, I am beginner in java. what i know about synchonized keyword is,If more that one 1 thread tries to access a particular resource we can lock the method using synchronized keyword. Then after that how the lock is released and how next thread access that.Please explain with example.Also explain object level lock and method level lock.
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3833

Rajendra Prakash wrote:Hi Friends, I am beginner in java. what i know about synchonized keyword is,If more that one 1 thread tries to access a particular resource we can lock the method using synchronized keyword.

When you have a synchronized method (or block), only one thread is allowed to execute that method (or block) at any given time.
Then after that how the lock is released and how next thread access that.

Lock is released whenever the thread is done with it (method in this case), so the JVM can assign another thread waiting for that lock.
Also explain object level lock and method level lock.

I haven't heard of "object level lock" (may be it's referring object lock ?) However there are two types of locks (monitors) in Java. Object lock & Class lock, those can be aquired by a thread. Class lock is per class basis & object lock is per object. If you have synchronized instance method(s) (or block), a thread wish to execute that method should aquire the lock for that particular object. Class lock is associated with the class. So any synchronized static method would need the class lock to be aquired by the thread which wish to execute that method. There are lot more to this but I suggest you go through Concurrency tutorial by Sun. And please CarefullyChooseOneForum when posting.


SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9303
    
  17

As Vijitha pointed out, the servlet forum is not the correct place for this question. I'll move it to the appropriate forum...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
 
GeeCON Prague 2014
 
subject: Synchronized with example