Initialisation paresseuse et modèles singleton

Optimiser son code en Java

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

Construire un client de cache Redis

  • Imaginons que nous construisions un client de cache qui interroge Redis
  • Notre client Redis est hébergé chez un prestataire tiers
  • Établir la connexion au client implique un appel réseau – supposons 500 ms

$$

Appel réseau pour établir la connexion Redis

Optimiser son code en Java

Une implémentation simple (hâtive)

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");
    }
}
  • Initialisation hâtive d'une connexion Redis
Optimiser son code en Java

Un problème potentiel avec cette approche

Cela paraît simple — et fonctionnerait — mais présente un risque potentiel

Et si nous n'avions finalement pas besoin du client Redis ?

  • Temps de démarrage gaspillé
  • Connexions inutiles établies
Optimiser son code en Java

Initialisation paresseuse

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;
    }
}
Optimiser son code en Java

Un autre problème avec notre approche

// 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 ...
Optimiser son code en Java

Le modèle singleton

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 ...
}
Optimiser son code en Java

Passons à la pratique !

Optimiser son code en Java

Preparing Video For Download...