允许多个获取同步getter/setter

Chi*_*pen 3 java concurrency multithreading synchronized

获得对字段的访问的常用方法是同步getter和setter.使用int的简单示例如下所示:

private int foo = 0;
public synchronized int get(){return this.foo;}
public synchronized void set(int bar){ this.foo = bar;}
Run Code Online (Sandbox Code Playgroud)

现在,虽然这是一种使访问线程安全的安全方法,但它也表明一次只能读取一个线程foo.

如果很多线程foo经常读取,并且有时只更新这个变量,那将是一个很大的浪费.相反,getter可以由多个线程同时调用而没有任何问题.

有关于如何处理这个问题的既定模式吗?或者你会如何以最优雅的方式解决这个问题?

Vik*_*ert 5

看一下ReadWriteLock.这个界面是你正在寻找的,它允许多个读者,但只允许一个作家.

一个例子:

private int foo = 0;

private ReadWriteLock rwLock = /* use some implementation of ReadWriteLock here */;

public int get() {
    Lock l = rwLock.readLock();
    int result = 0;
    l.lock();
    try {
        result = this.foo;
    }
    catch(Exception ex) {
        // may throw the Exception here
    }
    finally {
        l.unlock();
    }
    return result;
}

public void set(int bar){ 
    Lock l = rwLock.writeLock();
    l.lock();
    try {
        this.foo = bar;
    }
    catch(Exception ex) {
        // may throw the Exception here
    }
    finally {
        l.unlock();
    }
}
Run Code Online (Sandbox Code Playgroud)