Skip to main content

(How) can you resolve any issues with the thread lock code - I

Please review the code below.  How can you resolve issues if any. 

package com.javahowdoi.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockIssue {
    private int i;
    private Lock l = new ReentrantLock();

    public int getI() {
        try {
            l.lock();
            return i;
        } finally {l.unlock();}
    }

    public void setI(int i) {
        try {
            l.lock();
            reallySetI(i);
        } finally {l.unlock();}
    }

    private void reallySetI(int i ) {
        try {
            l.lock();
            this.i = i;
        } finally {l.unlock();}
    }

    public static void main(String[] args) {
        LockIssue li = new LockIssue();
        li.setI(100);
        System.out.println(li.getI());
    }

}

Answer is here

Comments