Inicialización perezosa y patrones singleton

Optimizing Code in Java

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

Crear un cliente de caché Redis

  • Imagina que estamos creando un cliente de caché que usa Redis
  • Nuestro cliente de Redis está alojado en un proveedor externo
  • Configurar la conexión requiere una llamada de red; imagina que tarda 500 ms

$$

Llamada por la red para establecer la conexión con Redis

Optimizing Code in Java

Una implementación simple (ansiosa)

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");
    }
}
  • Inicialización ansiosa de una conexión a Redis
Optimizing Code in Java

Un posible problema con este enfoque

Parece simple —y funcionaría—, pero tiene un posible problema

¿Qué pasa si no necesitamos el cliente de Redis?

  • Perdemos tiempo al iniciar
  • Establecemos conexiones innecesarias
Optimizing Code in Java

Inicialización perezosa

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;
    }
}
Optimizing Code in Java

Otro problema con nuestro enfoque

// 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 ...
Optimizing Code in Java

El patrón 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 ...
}
Optimizing Code in Java

¡Vamos a practicar!

Optimizing Code in Java

Preparing Video For Download...