Synchronization

S

sangeetay

hi ,
i would like to know hwta happens in this scenerio..
if a synchronized method calls an unsynchronized method. Does the
unsynchronized method behave as if it is synchronized automatically..
 
G

Gordon Beaton

if a synchronized method calls an unsynchronized method. Does the
unsynchronized method behave as if it is synchronized automatically..

Some pseudo code and names will help here:

public synchronized void outer() {
System.out.println("this method is synchronized");
/* some code... */
inner();
/* more code... */
}

public void inner() {
System.out.println("this method is unsynchronized");
/* some code... */
}

Only outer() is synchronized, and others are still free to call
inner() directly. Realize though that the original thread does not
leave outer() when it calls inner(), so outer() is still protected by
the synchronization during the time it executes inside inner().

/gordon
 
R

Roedy Green

i would like to know hwta happens in this scenerio..
if a synchronized method calls an unsynchronized method. Does the
unsynchronized method behave as if it is synchronized automatically..

It isn't unless there are no direct calls to the unsynchronised
method.

By analogy if you have a guard checking everyone coming into building,
you don't need one on every door once they get in.

The guard at the front door only lets one person into the building at
a time. There is no way than visitor can bump into any other people,
even if there are no such guards ensuring no more than one person to a
room.

synchronisation is like a guard ensuring but one thread at a time can
enter a region of code.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top