Object Locking Mechanism in Java

Say the customer has Credit Card. And he has a balance of the amount x, and he buys a yvaluable commodity (y<x). And again, he is going to buy another item that will cost z. ( y+z>x but z<x).

Now I can simulate this scenario in Java. If all transactions occur sequentially, there is no need to panic. A customer can buy a valuable item y, and then he does not have enough loans to buy another.

But when we come to a multi-threaded environment, we have to deal with some kind of blocking mechanism or some kind of strategy. Because if any other thread reads the credit card object, serious problems will be raised before reflecting the changes in the previous thread.

As far as I see one way, we can save a copy of the original balance, and we can check the current value immediately before updating the balance. If the value is the same as the original, we can make sure that other threads do not change the balance. If the balance is different, we must cancel our calculation.

Again, Java Synchronization is also a good solution. Now my question is what would be the best implementation approach in such a scenario?

Also, if we see this in the big picture. Synchronization affects system performance. Since it is locked, the object and the other thread must wait.

+4
source share
4 answers

ReadWriteLock, , , :

ReadWriteLock readWriteLock = new ReentrantReadWriteLock();


readWriteLock.readLock().lock();

    // multiple readers can enter this section
    // if not locked for writing, and not writers waiting
    // to lock for writing.

readWriteLock.readLock().unlock();


readWriteLock.writeLock().lock();

    // only one writer can enter this section,
    // and only if no threads are currently reading.

readWriteLock.writeLock().unlock();

ReadWriteLock . .

+3

. , .

- .

+2

, , . , , , , .

java.util.concurrent.atomic . . , AtomicInteger - :

AtomicInteger balance = new AtomicInteger();


void update(int change) throws InsufficientFundsException {
  int original, updated;
  do {
    original = balance.get();
    updated = original + change;
    if (updated < 0)
      throw new InsufficientFundsException();
  } while (!balance.compareAndSet(original, update));
}

, " ", , . , livelock.

, . concurrency, . , synchronized , -. , , , .

+2

, . , , , . , .

, AtomicInteger.compareAndSet() AtomicLong.compareAndSet() do.


synchronized CreditCard, . ( synchronized .)

, public synchronized boolean makePurchase(int cost), true false . , - , CreditCard (getBalance() setBalance()), - .

0

All Articles