当setter在Java中工作时,如何同步getter [英] How can I synchronize getter while a setter is working in Java

查看:103
本文介绍了当setter在Java中工作时,如何同步getter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个提供列表的静态类的多线程应用程序。我希望静态类的getter能够自由地工作(彼此不同步)但是当setter工作时我希望所有的getter都被锁定并等到setter的工作完成。我不想在调用它们时锁定getter,因为它会大大降低性能。吸气剂每天被称为1,000,000次,而且每天只能使用一次。

I am having a multi-thread application using a single static class which provides a list. I want getters of the static class to work freely (not synchronized against each other) but when a setter is working I want all getters to get locked and wait until setter's job is done. I don't want to lock getters when they are called together since it would degrade performance a lot. Getters are called 1,000,000 times per day and setter is only supposed to work once per day.

推荐答案

考虑使用 java.util.concurrent.locks.ReadWriteLock 实现,例如 ReentrantReadWriteLock (参见 javadoc

Consider using a java.util.concurrent.locks.ReadWriteLock implementation, such as ReentrantReadWriteLock (see javadoc)


A ReadWriteLock 维护一对关联的锁,一个用于只读操作,另一个用于写入。只要没有写入器,读锁定可以由多个读取器线程同时保持。写锁定是独占的。

A ReadWriteLock maintains a pair of associated locks, one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.

您将使用此而不是 synchronized 。你的getter将获得读锁定,然后在返回时释放,例如

You would use this instead of synchronized. Your getters would obtain the read lock, then release when they return, e.g.

public String getX() {
    Lock readLock = readWriteLock.readLock();
    readLock.lock();
    try {
        return value;
    } finally {
        readLock.unlock();
    }
}

同样适用于setters方法,但使用 readWriteLock.writeLock()而不是。

Similarly for setters methods, but using readWriteLock.writeLock() instead.

该类将有一个 ReentrantReadWriteLock 对象,由每个对象上的所有getter和setter共享(或者,如果你愿意,每个getter / setter对一个)。

The class would have a single ReentrantReadWriteLock object, shared by all getters and setters on each object (or, if you wish, one per getter/setter pair).

这很麻烦,但应该给予好处并发性。出于这些原因,如果你确实需要它,你应该只接受它,这意味着如果你只是使用vanilla同步,那么你可以测量降级的并发性。

It's quite cumbersome, but should give good concurrency. For those reasons, you should only take this on if you really need it, and that means measuring the degraded concurrency you get if you just use vanilla synchronization.

这篇关于当setter在Java中工作时,如何同步getter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆