Docsity

Java Thread Synchronization: wait(), notify() and Deadlocks - Prof. Douglas J. Wokoun, Assignments of Computer Science

Partial preview of the text

Download Java Thread Synchronization: wait(), notify() and Deadlocks - Prof. Douglas J. Wokoun and more Assignments Computer Science in PDF only on Docsity!

CS251 Intermediate Programming

Lecture 26

Threads

• Final next Monday, December 15.• Homework 6 due Wednesday.• Last quiz today.

recipient seldom coincide at the same method invocation.available to multi-threaded applications because the caller andmethod arguments and return values. This mechanism isn’tMethods in a single-threaded environment communicate by

same execution point so they are ready to exchange data.A mechanism is needed which brings multiple threads to the

wait()

and

notify()

are methods on

java.lang.Object

Callingdo this. (so they are inherited by every object) that provide a means to

wait()

causes the current

Thread

to stop executing

until another Thread calls

notify()

on the same

Object

wait()

and

notify()

can only be called from inside a

synchronized

block whose target is the same object as the

object whose

wait()

or

notify()

method is being called.

If you are calling

x.wait()

, you have to be inside a

synchronized(x)

block.

{ public class MyClass { public synchronized Object getNextThing()private List l; { while (this.l.size() == 0) // Wait until there is data available { try this.wait();

// Thread sleeps until some other Thread calls notify()

catch (InterruptedException ie) { }}

return this.l.remove(0);}

{ public synchronized void putNextThing(Object o)} this.notify(); // Will "wake" thread waiting for data, if there is anythis.l.add(o);

**{ public class BankAccount

  • /** Current balance. All access to this variable is controlled by the monitorprivate int number;**

*on the enclosing BankAccount instance /

{ public int getNumber()private double balance; return this.number;

{ public synchronized double getBalance()} return this.balance;

{ public synchronized void setBalance(double balance)} this.balance = balance;

{ public class BankAccount public static transfer(Account fromAccount, Account toAccount, double amount)/ This method is static because it affects two instances./** throws OverdraftException**

if (amount <= 0.0) throw new IllegalArgumentException("Transfer amount must be positive.");

if (newBalance < 0.0)double newBalance = fromBalance - amount;double fromBalance = fromAccount.getBalance(); throw new OverdraftException(newBalance);

toAccount.setBalance(toAccount.getBalance() + amount);fromAccount.setBalance(newBalance);

The

transfer()

(^) method

performs 3 operations:has a race condition. It

  1. Check suf

fi cient balance

in 1

st

account^

  1. Deduct money from 1
st

account

  1. Add money to 2
nd

account

Thread 1

Thread 2

Making the accessors and mutators

(^) synchronized

(^) prevents corruption of a

single object, but it doesn’t help coordinate multiple objects. The

(^) static

transfer()

(^) method also acquires and releases monitors as it enters and exits

synchronized

(^) instance members, leaving gaps where another thread can

alter the object. The

(^) static

(^) method needs to hold the monitors for both

objects for the entire time it’s executing...

Time

acct 1 has $

yes

Preemption

acct 1 has $

(^) yes

set acct 2 to $30set acct 1 to $

Preemption

set acct 3 to $30 set acct 1 to $

{ public class BankAccount public static transfer(Account fromAccount, Account toAccount, double amount)/ This method is static because it affects two instances./** throws OverdraftException**

if (amount <= 0.0) throw new IllegalArgumentException("Transfer amount must be positive.");

{ synchronized (fromAccount) { synchronized (toAccount) if (newBalance < 0.0)double newBalance = fromBalance - amount;double fromBalance = fromAccount.getBalance(); throw new OverdraftException(newBalance);

toAccount.setBalance(toAccount.getBalance() + amount);fromAccount.setBalance(newBalance);

times (when A thread that already holds a monitor can reacquire the same monitor multiple }

synchronized

(^) methods are called inside the

synchronized

(^) block).

Deadlocks are dif

fi

cult to debug.

No errors are generated when deadlocks occur.the call stack.The method calls that acquired the monitors could be deep inTheir manifestation is highly timing dependent.

Deadlocks are identi

fi

ed by the JVM thread trace mechanism,

which will identi

fi

ed the threads and objects involved.

Execute “kill -QUIT {pid}” from a Unix shellPress Control-Break from a Windows shell

Careful design, including analysis of possible control-

fl

ow paths

One technique is to always acquire monitors in a given order.is necessary to avoid deadlocks.

{ public class BankAccount public static transfer(Account fromAccount, Account toAccount, double amount) throws OverdraftException

if (amount <= 0.0) throw new IllegalArgumentException("Transfer amount must be positive.");

if (fromAccount.getNumber() < toAccount.getNumber())Account first, second; { first = fromAccount; second = toAccount; }

else { first = toAccount; second = fromAccount; }

{ synchronized (first) { synchronized (second) if (newBalance < 0.0)double newBalance = fromBalance - amount;double fromBalance = fromAccount.getBalance(); throw new OverdraftException(newBalance);

toAccount.setBalance(toAccount.getBalance() + amount);fromAccount.setBalance(newBalance);

{ public class BankAccount public static transfer(Account fromAccount, Account toAccount, double amount)/ This method is static because it affects two instances./** throws OverdraftException**

if (amount <= 0.0) throw new IllegalArgumentException("Transfer amount must be positive.");

toAccount.transaction(amount);fromAccount.transaction(-amount);