2

what is the difference between

public synchronized void addition()
{
   //something;
}

and

public void addtion()
{
     synchronized (//something)
     {
        //something;
     }
}

If I am wrong Ignore this question.

bdonlan
  • 224,562
  • 31
  • 268
  • 324
alishaik786
  • 3,696
  • 2
  • 17
  • 25
  • 1
    Possible [dupplicate](http://stackoverflow.com/questions/1149928/what-is-the-difference-between-a-synchronized-method-and-synchronized-block-in-j) – Artem Dec 15 '11 at 11:56

7 Answers7

5
public synchronized void addition() {...}

is equivalent to

public void addition() {
  synchronized(this) { ... }
}

Now, if you replace the this with a different object reference, the locking will be done using that other object's monitor.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

The second one doesn't compile. If you meant

public void addition()
{
     synchronized (this)
     {
        //something;
     }
}

Then they're equivalent.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
2

If the second example is synchronized (this), then there's no difference. If it's something else, then the lock object is different.

Joonas Pulakka
  • 36,252
  • 29
  • 106
  • 169
2
public synchronized void addition()
{
   //something;
}

is the same as:

public void addtion()
{
     synchronized (this)
     {
        //something;
     }
}

Whereas, in your second example, you may want to synchronize using something different from this.

Bruno
  • 119,590
  • 31
  • 270
  • 376
1

it the first one only one thread can execute whole method at a time whereas in second one only one thread can execute that synchronized block if not used this as parameter.

here is a duplicate of it Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

Community
  • 1
  • 1
Hemant Metalia
  • 29,730
  • 18
  • 72
  • 91
0

Synchronized method synchronizes on "this" object. And if it is a block you can choose any object as a lock.

dbf
  • 6,399
  • 2
  • 38
  • 65
0

I)

public synchronized void addition() 
{
    //something; 
}

II)

public void addtion() 
{      
    synchronized (//something)      
    {
        //something;      
    }
} 

In version I (method level synchronization), at a time, complete body of method can only be executed by one thread only.

however, version II is more flexible cause it's called block level synchronization and you can add some lines above synchronized (//something) to execute them parallely. it should be synchronized (this)

version II should be preferred as only that code needs to be multithreaded (within synchronized) which are critical.

Azodious
  • 13,752
  • 1
  • 36
  • 71