Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

thread synchronization

Hi,

I am working on below example

http://www.avajava.com/tutorials/lessons/how-do-i-use-a-synchronized-block-in-a-static-method.html


I have not understood what author is trying to demonstrate as below

It's possible to synchronize a static method. When this occurs, a lock is obtained for the class itself. This is demonstrated by the static hello() method in the SyncExample class below. When we create a synchronized block in a static method, we need to synchronize on an object, so what object should we synchronize on? We can synchronize on the Class object that represents the class that is being synchronized. This is demonstrated in the static goodbye() method of SyncExample. We synchronize on SyncExample.class.


I got below output which is not clear to me
hello
goodbye

please advise
Any links resources ideas highly appreciated. Thanks in advance
Avatar of mccarl
mccarl
Flag of Australia image

Yeah, that example is not that good because you would get the same output even if you remove the synchronize modifer/block.

The main point that it is trying to convey is that the two methods have the same functionality. Putting the synchronized keyword in the method declaration (like in hello() method) is essentially the same as using the synchronized block (like in goodbye() method) with this class as the argument, ie. SyncExample.class
Avatar of gudii9

ASKER

you would get the same output even if you remove the synchronize modifer/block.



you mean below synchronized block inside goodbye() method right?
public static void goodbye() {
            synchronized (SyncExample.class) {
                  System.out.println("goodbye");
            }
When you say removing  synchronize modifer/block means as below right comment those two lines?


public class SyncExample {

	public static void main(String[] args) {
		hello();
		goodbye();
	}

	public static synchronized void hello() {
		System.out.println("hello");
	}

	public static void goodbye() {
		//synchronized (SyncExample.class) {
			System.out.println("goodbye");
	//	}
	}

}

Open in new window

Can you please point me to better practical example on this concept to understand clearly.

Please advise
Avatar of gudii9

ASKER

Please advise
ASKER CERTIFIED SOLUTION
Avatar of mccarl
mccarl
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gudii9

ASKER

I'll try and get back to you soon with one.

Sure.
Avatar of gudii9

ASKER

using the synchronized block (like in goodbye() method) with this class as the argument, ie. SyncExample.class

Can there be synchronized blocks without any argument(like class name)?
Is that is possible?