Atomic construction

Bugs caused by multi-threading can be very difficult to find. Here’s one I encountered recently. private static MyObject INSTANCE; public void init() { if( INSTANCE == null) { initInstance(); } } private static synchronized void initInstance() { if( INSTANCE != null) { return; } INSTANCE = new MyObject(); INSTANCE.initThis(); INSTANCE.initThat(); } At first glance, this code is fine. It uses a synchronized static method to create the singleton, using double-checked locking to make sure it only gets created once. [Read More]

Synchronized code in distributed systems

I encountered some code recently where a GUI client was listening for Object updates from a multi-threaded server, and it was using the version number on the Object to determine whether the incoming Object was the latest version. The server incremented the version of the Object by inserting a new row into a table in the database and using the primary key as the version number. Now consider the case multi-threaded case where two threads, T1 and T2, are making updates to the Object. [Read More]