Java读写并发:读写锁 vs 锁+易失性

问题描述 投票:0回答:1

假设读者 = 10 x 作家,以下哪种解决方案在吞吐量方面更好。哪种解决方案更适合在生产代码中使用?

  1. 使用单锁进行set操作,使用易失性变量进行get操作
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;
        }

    }
}
  1. setget 操作使用单个读写锁
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 更便宜(基本上大部分时间都会被缓存)并且锁需要执行额外的指令

java concurrency locking volatile readwritelock
1个回答
0
投票

如果您仅将列表作为一个整体使用(用于设置或获取),我建议在您的函数中使用同步:

public synchronized void setInstances(List<Instance> newInstances) {
  instances = newInstances; 
}

public synchronized List<Instance> getInstances() {
  return instances;
}
© www.soinside.com 2019 - 2024. All rights reserved.