假设读者 = 10 x 作家,以下哪种解决方案在吞吐量方面更好。哪种解决方案更适合在生产代码中使用?
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public final class InstanceProvider {
private final Lock wLock = new ReentrantLock();
private volatile List<Instance> instances;
public void setInstances(List<Instance> newInstances) {
wLock.lock();
try {
instances = newInstances;
} finally {
wLock.unlock();
}
}
public List<Instance> getInstances() {
return instances;
}
@Getter
public static final class Instance {
private final String name;
public Instance(String name) {
this.name = name;
}
}
}
import java.util.List;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public final class InstanceProvider {
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private List<Instance> instances;
public void setInstances(List<Instance> newInstances) {
lock.writeLock().lock();
try {
instances = newInstances;
} finally {
lock.writeLock().unlock();
}
}
public List<Instance> getInstances() {
lock.readLock().lock();
try {
return instances;
} finally {
lock.readLock().unlock();
}
}
@Getter
public static final class Instance {
private final String name;
public Instance(String name) {
this.name = name;
}
}
}
我的假设是读取 volatile 更便宜(基本上大部分时间都会被缓存)并且锁需要执行额外的指令
如果您仅将列表作为一个整体使用(用于设置或获取),我建议在您的函数中使用同步:
public synchronized void setInstances(List<Instance> newInstances) {
instances = newInstances;
}
public synchronized List<Instance> getInstances() {
return instances;
}