制作静态ReentrantLocks [英] Making static ReentrantLocks
问题描述
I've stumbled upon this thread some time ago: Does making a reentrant lock static and make it a mutex? and I have an additional question on my own:
是否对创建private static final ReentrantLock lock
不被视为代码气味感兴趣?我已经读过静态变量是邪恶的,但是我目前正在使用的用例Im看起来是使用它的理想场所.
Im interested if creating a private static final ReentrantLock lock
is not considered a code smell? I've read that static variables are evil, yet my current use case Im working on looks like ideal place to use one.
有人愿意帮助吗?
编辑详细信息:我有这个课程,称为FileProcessor
,它在另一个线程中执行给定的工作.我的用例是分解此类的一些实例并完成这些工作.但是我要做的是确保只有一个人可以一次完成这项工作,并且轮流执行这项工作.
Edit with details: I have this class, call it FileProcessor
which does a given job in another thread. My use case is spinning up a few of these instances of this class and doing those jobs. But what I want to do is to make sure only one of them will make this job at once and they will take turns in performing the work.
所以我想出了病,给他们一个static ReentrantLock
,它将作为lock()
在run()
块中的第一件事,最后在unlock()
中.这样,他们就有了一个共享锁,可以保护处理同步.
So I figured out Ill give them a static ReentrantLock
that will lock()
as first thing in run()
block and unlock()
as last. This way they have a shared lock that will guard the processing synchronization.
谢谢.
推荐答案
在类级别使用静态Lock
进行同步是绝对正常的.您也可以使用
Using a static Lock
for synchronization at the class level is absolutely normal. You can also use
synchronized (FileProcessor.class) {
//your code
}
这篇关于制作静态ReentrantLocks的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!