← All challenges

BreakIt · Java Elite Technical Sprint · advanced · 7 min

The Broken Thread-Safe Singleton

A lazy-loading singleton database configuration client instance intermittently returns partially constructed data states.

The setup

You build a thread-safe singleton initialization layer to manage high-speed data client connection instances. Under high multi-threaded access spikes, threads occasionally receive a valid reference pointer to an object that is still incomplete.

The broken code

public class MasterDatabaseClient {
    private static MasterDatabaseClient coreInstance;
    private MasterDatabaseClient() { /* heavy resource configurations loaded here */ }

    public static MasterDatabaseClient getInstance() {
        // TRAP: Instruction re-ordering operations during runtime compilation allow 
        // instances to publish reference addresses before initializations wrap up!
        if (coreInstance == null) {
            synchronized (MasterDatabaseClient.class) {
                if (coreInstance == null) {
                    coreInstance = new MasterDatabaseClient();
                }
            }
        }
        return coreInstance;
    }
}

Hints

  1. Instantiating an object involves memory allocation, constructor execution, and reference assignment.
  2. Compilers can reorder these operations. Consequently, a thread might read a non-null reference before initialization concludes.
  3. Declare the instance volatile to insert a memory barrier that prevents instruction reordering.

The fix

public class MasterDatabaseClient {
    // Clean Fix: Introduce volatile visibility constraints to neutralize instruction re-ordering anomalies
    private static volatile MasterDatabaseClient coreInstance;
    private MasterDatabaseClient() { /* heavy resource configurations loaded here */ }

    public static MasterDatabaseClient getInstance() {
        if (coreInstance == null) {
            synchronized (MasterDatabaseClient.class) {
                if (coreInstance == null) {
                    coreInstance = new MasterDatabaseClient();
                }
            }
        }
        return coreInstance;
    }
}

Why it breaks

The Bug: The process `new MasterDatabaseClient()` is non-atomic. Java compiles this step into memory space allocations followed by reference assignments. Instruction reordering can publish the reference address prematurely, causing concurrent lookups to read incomplete states.

Related challenges: The Unresponsive Shutdown Switch · The Brittle Session Pruner