Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithread: Explicit locks

Tags:

java

I have a question about this lines of code:

class S1Es3SharedState {
    //lock
    private final Lock lock = new ReentrantLock();
    private int x = 0;

    public int getX() {
        lock.lock();
        try {
            return x;
        } finally  {
            lock.unlock();
        }
    }

    public void incrementX() {
        lock.lock();
        try {
            this.x = x++;
        } finally {
            lock.unlock();
        }
    }
}

the same object locks the statments in the method getX and in the method incrementX
what it mean?
If i understand it means that the same object is used to lock the statment of both methods, so, a thread can enter in one of these methods if both are free, it's right?

example:
ThreadA is inside in the getX method, now there is a context-switch so the ThreadA is waiting (inside the method) and the ThreadB is running and wants to enter in the getX() method but it can't because there is already the ThreadA. Also if the ThreadB needs to enter in the incrementX method still it cannot because the ThreadA is inside in the getX method. So the lock object i used allows to enter a thread just if both the methods are free (without threads that are running). it is possible? And this happen because i used the same object to lock getX and incrementX methods.

like image 642
Giovanni Far Avatar asked Jan 23 '26 01:01

Giovanni Far


1 Answers

It means that two different threads T1 and T2 cannot be getting
and incrementing the variable at the same moment of time.

Simply put return x; and this.x = x++; cannot be executed
at the same time by two different threads T1 and T2. The thread
which enters first wins, only when it's done and calls unlock,
the second one will have the chance to obtain the lock himself
and do his job.

like image 86
peter.petrov Avatar answered Jan 24 '26 23:01

peter.petrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!