Lazy initialization och singletonmönstret

Optimera kod i Java

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

Bygga en Redis-cacheklient

  • Vi bygger en cacheklient som använder Redis
  • Vår Redis-klient finns hos en tredjepartsleverantör
  • Anslutningen kräver ett nätverksanrop – tänk dig att det tar 500 ms

$$

Nätverksanrop för att upprätta Redis-anslutning

Optimera kod i Java

En enkel (eager) implementation

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 av en Redis-anslutning
Optimera kod i Java

Ett potentiellt problem med den här metoden

Det verkar enkelt – och fungerar – men det finns ett potentiellt problem

Vad händer om vi inte behöver Redis-klienten alls?

  • Vi slösar värdefull tid vid uppstart
  • Vi upprättar onödiga anslutningar
Optimera kod i 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;
    }
}
Optimera kod i Java

Ytterligare ett problem med vår lösning

// 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 ...
Optimera kod i Java

Singletonmönstret

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 ...
}
Optimera kod i Java

Nu kör vi en övning!

Optimera kod i Java

Preparing Video For Download...