Java Reference
In-Depth Information
Thisapplicationletsmoremoneybewithdrawnthanisavailableintheaccount.For
example,thefollowingoutputreveals$110beingwithdrawnwhenonly$100isavail-
able:
Wife withdraws $10: true
Wife withdraws $10: true
Husband withdraws $10: true
Wife withdraws $10: true
Husband withdraws $10: true
Wife withdraws $10: true
Husband withdraws $10: true
Husband withdraws $10: true
Husband withdraws $10: true
Husband withdraws $10: true
Husband withdraws $10: false
Husband withdraws $10: false
Husband withdraws $10: false
Husband withdraws $10: false
Wife withdraws $10: true
Wife withdraws $10: false
Wife withdraws $10: false
Wife withdraws $10: false
Wife withdraws $10: false
Wife withdraws $10: false
Thereasonwhymoremoneyiswithdrawnthanisavailableforwithdrawalisthata
race condition exists between the husband and wife threads.
Note A race condition isascenarioinwhichmultiplethreadsupdatethesameobject
atthesametimeornearlyatthesametime.Partoftheobjectstoresvalueswrittento
it by one thread, and another part of the object stores values written to it by another
thread.
Theraceconditionexistsbecausetheactionsofcheckingtheamountforwithdrawal
toensurethatitislessthanwhatappearsinthebalanceanddeductingtheamountfrom
thebalancearenot atomic (indivisible)operations.(Althoughatomsaredivisible, atom-
ic is commonly used to refer to something being indivisible.)
Note The Thread.sleep() methodcallthatsleepsforavariableamountoftime
(uptoamaximumof199milliseconds)ispresentsothatyoucanobservemoremoney
Search WWH ::




Custom Search