Java:在基元上同步吗? [英] Java: Synchronizing on primitives?

查看:58
本文介绍了Java:在基元上同步吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的系统中,我们有一种方法,当使用特定ID进行调用时,该方法可以完成一些工作:

In our system, we have a method that will do some work when it's called with a certain ID:

public void doWork(long id) { /* ... */ }

现在,可以完成此工作同时使用不同的ID,但是如果用2个线程使用相同的ID调用该方法,则应阻塞一个线程直到完成。

Now, this work can be done concurrently for different IDs, but if the method is called with the same ID by 2 threads, one thread should block until it's finished.

最简单的解决方案是使用从Long ID映射到我们可以锁定的任意对象的映射。我预见到的一个问题是我们可以在系统中拥有大量ID,并且该地图每天都在增长。

The simplest solution would be to have a Map that maps from the Long ID to some arbitrary object that we can lock on. One problem I foresee with this is that we can have tons of IDs in the system and this map will keep growing every day.

理想情况下,我认为我们需要一个系统,我们每个线程都会获取一个锁对象,并在可能的情况下进行锁,然后进行工作,然后发出信号说明已完成该锁。如果很明显没有其他人在使用此特定的锁,则可以安全地将其从锁映射中删除,以防止内存泄漏。

Ideally, I think we need a system where we each thread will fetch a lock object, lock when possible, do the work, then signal that we're done with the lock. If it's clear that nobody else is using this particular lock, then safely remove it from the lock map to prevent the memory leak.

我想这肯定是很常见的情况所以我希望有一个现有的解决方案。有人知道吗?

I imagine this must be a pretty common scenario so I'm hoping there is an existing solution out there. Anyone know of any?

推荐答案

我前段时间为自己发明了类似的东西。我称它为等价类锁,意思是,它锁上所有与给定事物相等的事物。您可以从我的github 中获取它,然后如果需要的话,可以使用Apache 2许可证,或者直接阅读并忘记它!

I invented a thing like that for myself some time ago. I call it an equivalence-class lock, meaning, it locks on all of the things that are equal to the given thing. You can get it from my github, and use it subject to the Apache 2 license, if you like, or just read it and forget it!

这篇关于Java:在基元上同步吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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