Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locking mechanism for object in Java

Let's say customer has a Credit Card. And he has balance of x amount of money and he is buying y valued item(y<x). And again he is going to buy another item witch will cost z. (y+z>x but z<x) .

Now I am going to simulate this scenario in Java. If all transaction happens in sequential, there is no need to panic. Customer can buy y valued item and then he don't have enough credit to buy other one.

But when we come in to multi-threaded environment we have to deal with some locking mechanism or some strategy. Because if some other thread read credit card object before reflect changes by previous thread serious issues will rise.

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.

And again Java Synchronization also a good solution. Now my question is what will be the best approach to implement in such a scenario?

Additionally if we are going to see this in big picture. Synchronization hits the performance of the system. Since it is locked the object and other thread has to wait.

like image 990
Ruchira Gayan Ranaweera Avatar asked Mar 21 '23 14:03

Ruchira Gayan Ranaweera


2 Answers

I will prefer to have a ReadWriteLock, this helps to to lock it for reading and writing, this is nice because you can have separate read and write lock for each resource:

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 internally keeps two Lock instances. One guarding read access, and one guarding write access.

like image 195
tokhi Avatar answered Apr 07 '23 02:04

tokhi


Your proposal doesn't fit. You can't be sure the context switch doesn't happen between check and update.

The only way is synchronization.

like image 30
Dario Avatar answered Apr 07 '23 02:04

Dario