Inizializzazione lazy e pattern singleton

Ottimizzazione del codice in Java

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

Creare un client cache Redis

  • Immagina di creare un client cache che usa Redis
  • Il client Redis è ospitato da un provider terzo
  • Configurare la connessione richiede una chiamata di rete: ipotizza 500 ms

$$

Chiamata di rete per stabilire la connessione a Redis

Ottimizzazione del codice in Java

Una semplice implementazione (eager)

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");
    }
}
  • Inizializzazione eager della connessione Redis
Ottimizzazione del codice in Java

Un possibile problema di questo approccio

Sembra semplice — e funziona — ma ha un potenziale problema

E se il client Redis non servisse?

  • Tempo di avvio sprecato
  • Connessioni inutili
Ottimizzazione del codice in Java

Inizializzazione lazy

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;
    }
}
Ottimizzazione del codice in Java

Un altro problema del nostro approccio

// 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 ...
Ottimizzazione del codice in Java

Il pattern 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 ...
}
Ottimizzazione del codice in Java

Passons à la pratique !

Ottimizzazione del codice in Java

Preparing Video For Download...