Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>As far as I can see one way is we can keep a copy of original balance and we can check current value just before update the balance. If value is same as original one then we can make sure other threads doesn't change the balance. If balance different then we have to undo our calculation.</p> </blockquote> <p>Sounds like what <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicInteger.html#compareAndSet%28int,%20int%29" rel="nofollow"><code>AtomicInteger.compareAndSet()</code></a> and <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicLong.html#compareAndSet%28long,%20long%29" rel="nofollow"><code>AtomicLong.compareAndSet()</code></a> do.</p> <hr> <p>An easier-to-understand approach would involve using <code>synchronized</code> methods on your <code>CreditCard</code> class that your code would call to update the balance. (Only one <code>synchronized</code> method on an object can execute at any one time.) </p> <p>In this case, it sounds like you want a <code>public synchronized boolean makePurchase(int cost)</code> method that returns <code>true</code> on success and <code>false</code> on failure. The goal is that no transaction on your object should require more than one method call - as you've realized, you won't want to make two method calls on <code>CreditCard</code> (<code>getBalance()</code> and later <code>setBalance()</code>) to do the transaction, because of potential race conditions.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload