What is the difference between function synchronization and object synchronization?Explain with an example.

Showing Answers 1 - 2 of 2 Answers

debabrat panda

  • Sep 25th, 2006
 

hi

synchronize method

 To synchronize an entire method, you just include the synchronized keyword as one of the method qualifiers, as in:

class syncDemo{

synchronized void test{

//your synchronized  code

}

synchronize object

 To create a synchronized object, you use the synchronized  keyword with an expression that evaluates to an object reference, as in

class syncDemo{

void test{

synchronized (this){

//your synchronized  code

}

regards

Deb

 

}

  Was this answer useful?  Yes

intalaash

  • Sep 28th, 2006
 

function or method synchronization synchronizes entire method i.e.synchronized void MyMethod(){...}this will place a lock on the object until current thread finishes execution. This ensures that MyMethod is always accessed by a single thread at a time.But consider this,void MyMethod(){.... someOtherMethod();..}Here you might need to just make sure that call to someOtherMethod() is synchronized, so instead of making entire method synchronized, you just make a synchronized block around someOtherMethod()void MyMethod(){....synchronize{ someOtherMethod();}..}This improves perfomance by locking object for shorter duration.Of-course you need to analyze your code correctly for doing this. There is not straight forward answer as to when to use Synchronize method vs Synchronize block.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions