my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes synchronized  keyword use Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "synchronized  keyword use" Watch "synchronized  keyword use" New topic

synchronized keyword use

samdeep aarzoo
Ranch Hand

Joined: Jun 09, 2005
Posts: 160
how can we use synchronized keyword in method and block in threads question
and why synchronized keyword is used in stringbuffer methods
please help
Shaila Vijaya Raja

Joined: Apr 09, 2005
Posts: 23
Consider your class name as Test.

you have created a object as

Test te1 = new Test();
Test te2 = new Test();

Thread t1 = new Thread(te1);
Thread t2 = new Thread(te1);
Thread t3 = new Thread(te2)

now t1 and t2 are two thread class reference having the same object te1.

but t3 is the thread having a different object.

Keep in mind that each and every object has a lock on its own.

And you are having three seperate methods method1()method2() and method3() in your class and method1() and method2() are marked as synchronized.

Now consider your t1 is accessing the method1()( now the object te1 lock is owned by the thread t1 because method1() is synchronized).

now no other threads (example t2) having the same object te1 cannot access any other synchronized method in the class Test. but can access nonsynchronized method.

But the thread having the different object( example: t3) can acess a synchronized or non synchronized method.

If your synchronized method is marked as static then the whole class is said to be locked. In such a case, even no other thread having a different object(example t3) can access the synchronized method. But all the nonsynchronized method shall be accessed by any other threads.

With Regards
Shaila Vijaya Raja

With Regards,<br />Shaila Vijaya Raja<br /> <br />SCJP1.4
samdeep aarzoo
Ranch Hand

Joined: Jun 09, 2005
Posts: 160
thanks shailavijayaraja ramasamy
thank u very much for this nice explanation
I agree. Here's the link:
subject: synchronized keyword use
jQuery in Action, 3rd edition