0

Possible Duplicate:
What is the difference between a synchronized method and synchronized block in Java?
What is the difference between a synchronized function and synchronized block?

i dont understand the difference between these 2 codes for threading i believe it is for mutual exclusion but i dont understqnd whats the difference can you help me?

public synchronized void Method1 () {
  }

public myFunction (){
       synchronized (this) { 
     }
 }

Thanks for the help.

Community
  • 1
  • 1
darkuzul
  • 63
  • 1
  • 1
  • 11
  • 1
    or http://stackoverflow.com/questions/1149928/what-is-the-difference-between-a-synchronized-method-and-synchronized-block-in-j – bdonlan Apr 17 '12 at 06:00

5 Answers5

3

The only difference is reducing a number of operations guarded by a lock which can improve performance much.

Example: let's imagine we have a servlet which gives an array of factors of a big number on input, and we want to count how often the servlet is launched. The problem is synchronizing the access to the state variable requestsCount

//Poor performance
class PoorFactorizer implements Servlet {
    private int requestsCount = 0;
    public synchronized void service(ServletRequest req, ServletResponse res) {
        BigInteger numberToFactorize = extractFromRequest(req);
        BigInteger[] factors = factorize(numberToFactorize); // long lasting
                                 // operation makes everyone wait 
        requestCount++;
        encodeResponse(res, factors);
    }
}

//Better perfomance
class PoorFactorizer implements Servlet {
    private int requestsCount = 0;
    public void service(ServletRequest req, ServletResponse res) {
        BigInteger numberToFactorize = extractFromRequest(req);
        BigInteger[] factors = factorize(numberToFactorize); 
        // since we need to guard only the class' state
        // let's guard only the operation with the state
        synchronized(this) {            
            requestCount++;
        }
        encodeResponse(res, factors);
    }
}  

UPD: you can read a very good explanation in a masterpiece "Java Concurrency in Practice" (chapter 2). I highly recommend to read this book from cover to cover.

Andrey Atapin
  • 7,745
  • 3
  • 28
  • 34
0

The difference is the granularity of the mutual exclusion. With your code above, only one thread can call Method1 at a time; multiple threads can potentially call myFunction. However, since myFunction does nothing other than enter a block synchronized on 'this', there's no practical difference. But, myFunction could potentially include other code outside of the synchronized guard which could be executed concurrently by multiple threads.

Rich Drummond
  • 3,439
  • 1
  • 15
  • 16
0

From locking perspective both behave the same. The only difference can be is that there can any non-null object used for a synchroized block ie.

public myFunction (){
   synchronized (anyObject) { 
 }
}

Now this block can be synchronized based on this object.

Where as for the case where the synchronized keyword was used , its synchronization scope depends on the calling object.

Hope this has helped you. Enjoy Coding!!!

Sri Harsha
  • 319
  • 1
  • 4
  • 12
0

If you have a method

public synchronized void methodA()
{
    while(condition)
    {
        // do Something That Takes A Minute ;
    } 
    // do Something That Needs A Lock;
    while(condition)
    {
        // do Something That Takes Another Minute ;
    } 
}

It will hold lock for 2 minutes more than

public void methodA()
{
    while(condition)
    {
        // do Something That Takes A Minute ;
    } 
    synchronized(this)
    {
        // do Something That Needs A Lock;
    } 
    while(condition)
    {
        // do Something That Takes Another Minute ;
    } 
}

In case of highly concurrent applications, that difference in the time for which the lock is held is very significant.

Arguably you can break the method 2 down into 2 methods and apply synchronized at method level, but that might at times lead to bad code.

SO both facilities are provided by Java.

0

See the difference

  • when you synchronize method, method is implicitly locked by this object and you locked entire method even though everything might not be critical to lock. (performance degradation).

  • when you synchronize your block, you have chosen the critical code for the locking(performance improvement) and you can choose locking object. [Lets say you have multiple object performing important action e.g book available seat and you have multiple request for booking. You might not allow everyone to book at same time nor you want to lock on this(current object). In this scenario you need to have common object to take lock and perform operation. At a time, Lock can be acquired by any one object. Thus, you guarantee only one requester book ticket at a time. Hence, no duplicate booking allowed].

neo
  • 1,054
  • 1
  • 10
  • 19