Reputation: 33
when I have a method like
public void unsynchronizedMethod(){
callSynchronizedMethod();
//dosomestuff after this line
}
does it mean that all content, after calling callSynchronizedMethod() in the unsynchronizedMethod()-Method, is implicitly synchronized?
Upvotes: 3
Views: 947
Reputation: 15656
No, there wont be an implicit synchronisation. Synchronized works within a block or function scope. Anything outside a synchronized block is not synchronized.
The following example code shows that. If the methods where synchronized it would always print 0.
class example extends Thread{
//Global value updated by the example threads
public static volatile int value= 0;
public void run(){
while(true)//run forever
unsynchMethod();
}
public void unsynchMethod(){
synchronizedMethod();
//Count value up and then back down to 0
for(int i =0; i < 20000;++i)
value++;//reads increments and updates value (3 steps)
for(int i = 0; i < 20000;++i)
value--;//reads decrements and updates value (3 steps)
//Print value
System.out.println(value);
}
//Classlevel synchronized function
public static synchronized void synchronizedMethod(){
//not important
}
public static void main(String... args){
example a = new example();
example b = new example();
a.start();
b.start();
}
}
My Results, should have been 0 if synchronized:
4463
6539
-313
-2401
-3012
...
Upvotes: 0
Reputation: 384016
Synchronization is defined in a straightforward manner:
synchronized
method: within the execution of that methodsynchronized
block: within the execution of that blockHere are the relevant excerpts from Java Language Specification 3rd Edition:
synchronized
StatementA
synchronized
statement:
- acquires a mutual-exclusion lock on behalf of the executing thread,
- executes a block,
- then releases the lock.
While the executing thread owns the lock, no other thread may acquire the lock.
synchronized
methods is semantically identical to a synchronized
statement applied to the whole method (§JLS 8.4.3.6. The lock is obtained from either this
(if it's an instance method) or the Class
object associated with the method's class (if it's a static
method; you can't refer to this
in a static
context).
So to answer the original question, given this snippet:
public void unsynchronizedMethod(){
callSynchronizedMethod();
doSomeUnsynchronizedStuff(); // no "implicit synchronization" here
}
Note that this is by design: you should always strive to minimize synchronization to only critical sections. Outside of those critical sections, there is no lingering effect from earlier synchronization.
Upvotes: 3
Reputation: 11497
No, it's not.
Synchronized means that only one thread at a time will execute the code.
But after callSynchronizedMethod()
the threads could run again over the code in different order, all at at the same time.
Upvotes: 0
Reputation: 346536
No. The lock is released at the end of callSynchronizedMethod()
.
Upvotes: 7