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.
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.
The pseudo-code:
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 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:
It’s not a classic double-checked lock problem assuming
dao().fetchis properly mutexed from the create method.Edit: (code was updated)
The classic problem of a double-checked lock is having a value assigned before initialization occurs where two threads are accessing the same value.
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.