这是双重检查锁定吗? [英] Is this broken double checked locking?
问题描述
Checkstyle将此代码报告为双重检查锁定习惯用法已损坏,但我认为我的代码实际上并未受到双重检查锁定问题的影响。
Checkstyle reports this code as "The double-checked locking idiom is broken", but I don't think that my code actually is affected by the problems with double-checked locking.
如果具有该id的行不存在,则代码应该在数据库中创建一行。它在多线程环境中运行,我想避免主键存在的SQL异常。
The code is supposed to create a row in a database if a row with that id doesn't exist. It runs in a multi-threaded environment and I want to avoid the primary-key-exists SQL-exceptions.
伪代码:
private void createRow(int id) {
Row row = dao().fetch(id);
if (row == null) {
synchronized (TestClass.class) {
row = dao().fetch(id);
if (row == null) {
dao().create(id);
}
}
}
}
I可以同意它看起来像双重检查锁定,但我没有使用静态变量,fetch()和create()中的代码可能太复杂而无法内联并且无序。
I can agree that it looks like double-checked locking, but I am not using static variables and the code in fetch() and create() is probably too complex to be inlined and put out of order.
我错了还是格式? :)
Am I wrong or checkstyle? :)
推荐答案
假设您想要读取最内线:
Assuming you want that innermost line to read:
row = dao().create(id);
假设 dao(),这不是经典的双重检查锁定问题。
与create方法正确互斥。
It's not a classic double-checked lock problem assuming dao().fetch
is properly mutexed from the create method.
编辑 :(代码已更新)
双重检查锁的经典问题是在初始化发生之前分配了一个值,其中两个线程正在访问相同的值。
The classic problem of a double-checked lock is having a value assigned before initialization occurs where two threads are accessing the same value.
假设DAO正确同步并且不会返回部分初始化的值,这不会受到双重检查锁定习惯的缺陷的影响。
Assuming the DAO is properly synchronized and will not return a partially initialized value, this doesn't suffer from the flaws of the double-checked lock idiom.
这篇关于这是双重检查锁定吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!