ConcurrentSkipListSet并替换remove(key)

发布于 2024-11-16 21:29:11 字数 969 浏览 8 评论 0原文

我正在使用 ConcurrentSkipListSet,其中填充了 20 个键。

我想不断地更换这些钥匙。然而,ConcurrentSkipListSet似乎没有原子替换功能。

这就是我现在使用的:

    ConcurrentSkipListSet<Long> set = new ConcurrentSkipListSet<Long>();
    AtomicLong uniquefier = new AtomicLong(1);    

    public void fillSet() { 
    // fills set with 20 unique keys;
    }
    public void updateSet() {
        Long now = Calendar.getInstance().getTimeInMillis();
        Long oldestKey = set.first();
        if (set.remove(oldestKey)) {
            set.add(makeUnique(now));
        }
    }

    private static final long MULTIPLIER = 1024;

    public Long makeUnique(long in) {
        return (in*MULTIPLIER+uniquefier.getAndSet((uniquefier.incrementAndGet())%(MULTIPLIER/2)));
    }

整个操作的目标是保持列表不变,并且仅通过替换来更新。 updateSet 每毫秒被调用约 100 次。

现在,我的问题是:如果元素本身在之前(并且不在之后)存在,则remove是否返回true,或者如果调用实际上负责删除,则该方法是否仅返回true? 即:如果多个线程同时对同一个键调用remove,它们/全部/会返回true,还是只有一个线程返回true?

I am using ConcurrentSkipListSet, which I fill with 20 keys.

I want to replace these keys continuously. However, ConcurrentSkipListSet doesn't seem to have an atomic replace function.

This is what I am using now:

    ConcurrentSkipListSet<Long> set = new ConcurrentSkipListSet<Long>();
    AtomicLong uniquefier = new AtomicLong(1);    

    public void fillSet() { 
    // fills set with 20 unique keys;
    }
    public void updateSet() {
        Long now = Calendar.getInstance().getTimeInMillis();
        Long oldestKey = set.first();
        if (set.remove(oldestKey)) {
            set.add(makeUnique(now));
        }
    }

    private static final long MULTIPLIER = 1024;

    public Long makeUnique(long in) {
        return (in*MULTIPLIER+uniquefier.getAndSet((uniquefier.incrementAndGet())%(MULTIPLIER/2)));
    }

The goal of this whole operation is to keep the list as long as it is, and only update by replacing. updateSet is called some 100 times per ms.

Now, my question is this: does remove return true if the element itself was present before (and isn't after), or does the method return true only if the call was actually responsible for the removal?
I.e.: if multiple threads call remove on the very same key at the very same time, will they /all/ return true, or will only one return true?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只怪假的太真实 2024-11-23 21:29:11

set.remove 只会对实际导致对象被删除的线程返回 true。

集合并发性背后的想法是多个线程可以更新多个对象。然而,每个单独的对象一次只能由一个线程更新。

set.remove will only return true for the thread that actually caused the object to be removed.

The idea behind the set's concurrency is that multiple threads can be updating multiple objects. However, each individual object can only be updated by one thread at a time.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文