Lazy Initialization und Singleton-Pattern

Codeoptimierung in Java

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

Einen Redis-Cache-Client bauen

  • Stell dir vor, wir bauen einen Cache-Client, der Redis anfragt
  • Unser Redis-Client läuft bei einem Drittanbieter
  • Das Einrichten der Verbindung braucht einen Netzwerkaufruf – stell dir 500 ms vor

$$

Anruf über das Netzwerk, um die Redis-Verbindung herzustellen

Codeoptimierung in Java

Eine einfache (eager) Implementierung

public class RedisCache {
    // The client library we use to connect to Redis
    private final RedisClient client;

    public RedisCache() {
        // The connection is setup inside the constructor
        connection = new RedisClient("cache.mycompany.com");
    }
}
  • Eager Initialization einer Redis-Verbindung
Codeoptimierung in Java

Ein mögliches Problem bei diesem Ansatz

Das wirkt simpel – und würde funktionieren –, hat aber ein mögliches Problem

Was, wenn wir den Redis-Client gar nicht brauchen?

  • Wir verschwenden wertvolle Startzeit
  • Wir bauen unnötige Verbindungen auf
Codeoptimierung in Java

Lazy Initialization

public class RedisCache {
    private RedisClient client;

    // Instead of setting up the connection in the constructor,
    // we only set it up when someone needs to get the client.
    public RedisClient getClient() {
        if (connection == null) {
            connection = new RedisClient("cache.mycompany.com");
        }
        return connection;
    }
}
Codeoptimierung in Java

Ein weiteres Problem unseres Ansatzes

// UserService needs cache access
public class UserService {
    private RedisCache userCache = new RedisCache();  // First connection
}

// PaymentService also needs cache
public class PaymentService {
    private RedisCache paymentCache = new RedisCache();  // Second connection
}

// ...same for OrderService ...
Codeoptimierung in Java

Das Singleton-Pattern

public class RedisCache {
    private static RedisCache instance;
    private RedisClient client;

    // The constructor is private so that we ensure we only
    // create RedisCache inside this class
    private RedisCache() {}

    public static RedisCache getInstance() 
        // We only create a RedisCache if one does not already exist
        if (instance == null) { instance = new RedisCache(); }
        return instance;
    }

    // ... The rest is the same as before ...
}
Codeoptimierung in Java

Lass uns üben!

Codeoptimierung in Java

Preparing Video For Download...