【发布时间】:2012-05-10 15:26:08
【问题描述】:
我有一个共享的临时文件资源,它被分成 4K 的块(或一些这样的值)。文件中的每个 4K 都由一个从零开始的索引表示。对于这个共享资源,我跟踪正在使用的 4K 块索引,并始终返回索引最低的未使用的 4K 块,如果全部都在使用,则返回 -1。
这个索引的 ResourceSet 类有一个公共的获取和释放方法,两者都使用同步锁,其持续时间大约类似于生成 4 个随机数的时间(昂贵,cpu-wise)。
因此从后面的代码可以看出,我在acquire()上使用了一个AtomicInteger“计数信号量”来防止大量线程同时进入临界区,返回-1(不可用对现在)如果线程太多。
目前,我使用 100 的常量用于紧密的 CAS 循环以尝试增加获取中的原子整数,并使用 10 的常量用于允许进入临界区的最大线程数,这足够长制造争用。我的问题是,对于有多个线程试图访问这些 4K 块的中等到高负载的 servlet 引擎,这些常量应该是什么?
public class ResourceSet {
// ??? what should this be
// maximum number of attempts to try to increment with CAS on acquire
private static final int CAS_MAX_ATTEMPTS = 50;
// ??? what should this be
// maximum number of threads contending for lock before returning -1 on acquire
private static final int CONTENTION_MAX = 10;
private AtomicInteger latch = new AtomicInteger(0);
... member variables to track free resources
private boolean aquireLatchForAquire ()
{
for (int i = 0; i < CAS_MAX_ATTEMPTS; i++) {
int val = latch.get();
if (val == -1)
throw new AssertionError("bug in ResourceSet"); // this means more threads than can exist on any system, so its a bug!
if (!latch.compareAndSet(val, val+1))
continue;
if (val < 0 || val >= CONTENTION_MAX) {
latch.decrementAndGet();
// added to fix BUG that comment pointed out, thanks!
return false;
}
}
return false;
}
private void aquireLatchForRelease ()
{
do {
int val = latch.get();
if (val == -1)
throw new AssertionError("bug in ResourceSet"); // this means more threads than can exist on any system, so its a bug!
if (latch.compareAndSet(val, val+1))
return;
} while (true);
}
public ResourceSet (int totalResources)
{
... initialize
}
public int acquire (ResourceTracker owned)
{
if (!aquireLatchForAquire())
return -1;
try {
synchronized (this) {
... algorithm to compute minimum free resoource or return -1 if all in use
return resourceindex;
}
} finally {
latch.decrementAndGet();
}
}
public boolean release (ResourceIter iter)
{
aquireLatchForRelease();
try {
synchronized (this) {
... iterate and release all resources
}
} finally {
latch.decrementAndGet();
}
}
}
【问题讨论】:
-
你有代码要分享吗?
-
我刚刚添加了代码来显示我在做什么。
-
请写的重点准确。
-
在达到 contention_max 后,此代码是否会出现错误,因为该方法将返回 false,然后从不调用递减。
-
@benmmurphy -- 很棒的电话,让我在测试中省去了很多痛苦!
标签: java multithreading mutex critical-section lock-free