我正在实现请求实例的FIFO队列(预先分配的请求对象以获得速度),并在add方法上使用"synchronized"关键字开始.该方法非常短(检查固定大小缓冲区中的空间,然后向数组添加值).使用visualVM看起来线程比我更喜欢阻塞("监视器"准确).因此,我将代码转换为使用AtomicInteger值,例如跟踪当前大小,然后在while循环中使用compareAndSet()(因为AtomicInteger在内部为incrementAndGet()等方法执行).代码现在看起来要长一点.
我想知道的是使用synchronized和更短代码的性能开销与没有synchronized关键字的更长代码相比(因此永远不应该阻塞锁).
这是使用synchronized关键字的旧get方法:
public synchronized Request get()
{
if (head == tail)
{
return null;
}
Request r = requests[head];
head = (head + 1) % requests.length;
return r;
}
Run Code Online (Sandbox Code Playgroud)
这是没有synchronized关键字的新get方法:
public Request get()
{
while (true)
{
int current = size.get();
if (current <= 0)
{
return null;
}
if (size.compareAndSet(current, current - 1))
{
break;
}
}
while (true)
{
int current = head.get();
int nextHead = (current + 1) % requests.length;
if (head.compareAndSet(current, nextHead))
{
return requests[current]; …Run Code Online (Sandbox Code Playgroud)