简体   繁体   中英

Lock an object in Java

How can a Java object be locked for a certain amount of time (eg 20 seconds)? By locked, I mean that the object cannot be accessed in that time.

You could synchronize all of the methods, and have a lock method that just waits for 20 seconds and returns.

 public  synchronized void lock(){
            try {
                Thread.sleep(20 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
        }

Remember the synchronize all of the methods, and keep all fields private. (Everything on the interface should be synchronized )

If you need to do this for a general object - ie, one you can't write or specify yourself - then it's time to learn how Monads work:

public class Lockable<T> {

    private T _t;
    public Lockable(T t){
        _t = t;
    }

    public synchronized void perform(Consumer<T> consumer){
        consumer.accept(_t);
    }

    public synchronized <R> R get(Function<T, R> function){
        return function.apply(_t);
    }

    public synchronized<R> Lockable<R> map(Function<T, R> function){
        return new Lockable(function.apply(_t));
    }

    public synchronized void lock(){
        try {
            Thread.sleep(20 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread.interrupt();
        }
    }

}

The above isn't 100% unbeatable, but so long as you'd don't let un-wrapped references loose, it should be okay.

There is no general mechanism to lock objects in Java.

You can define your own class of lockable objects (eg, as suggested by David Pérez Cabrera and Edward Peters), but there is no way to lock arbitrary objects that weren't designed to be lockable.

To be more precise, all of its method must be synchronized and all of its field must be private .

public class LockeableObject {

    private String fieldFoo;

    public synchronized void lock() throws InterruptedException{
        this.wait(20 * 1000); // 20 seconds
    }

    public synchronized void foo() {
         ...
    }

    public synchronized void foo2() {
         ...
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM