views:

149

answers:

3

Can non synchronized methods called from synchronized methods allow a thread to block?

public synchronized void foo(){
 someStuff();
 someMoreStuff();
 bar();
}

public void bar(){
 //... does some things
}

If a thread is executing foo() is there anyway to ensure that bar() will be called before the thread sleeps?

TIA

+3  A: 

A thread can always be pre-empted (there's no way of preventing that in Java) but no other thread will be able to acquire the lock on the same object before foo returns.

Note that a thread "losing the CPU" isn't what's normally meant by "blocking" - normally a call is deemed to block if it needs to wait for something else to occur. For example:

  • Reading from a stream blocks until there is some data available (or the end of the stream is reached)
  • Acquiring a lock blocks until the lock is available

These are very different from just running out of time slice.

Jon Skeet
Thanks for the clarification, this stuff is not trivial :)
javamonkey79
+1  A: 

Are you asking if there's a way to insure that the Java VM doesn't take the CPU and let another thread execute? You could set the Thread priority to high, but this still wouldn't provide a guarantee at all.

No other thread will be able to call your "foo" method while you don't have the CPU, though. Similarly, synchronizing "bar" would prevent it from being called until your call to "foo" had completed (as you own the lock for the entire period of the "foo" method).

jsight
+1  A: 

The question seems to be if other threads can freely invoke bar() while one thread holds the lock on an object during the execution of foo(). And specifically, if two or more threads can be running bar() at the same time.

And the answer is that any thread can run bar() at any time, so yes, there can be more than one thread running bar() at any single point in time.

Ringding