Inicialização preguiçosa e padrões singleton

Otimização de Código em Java

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

Criando um cliente de cache Redis

  • Imagine que estamos criando um cliente de cache que usa Redis
  • Nosso cliente Redis fica em um provedor terceirizado
  • Configurar a conexão envolve uma chamada de rede — imagine que leva 500 ms

$$

Chamada pela rede para estabelecer conexão com o Redis

Otimização de Código em Java

Uma implementação simples (adiantada)

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");
    }
}
  • Inicialização adiantada de uma conexão Redis
Otimização de Código em Java

Um possível problema nessa abordagem

Parece simples — e funcionaria — mas tem um possível problema

E se a gente nem precisar do cliente Redis?

  • Perdemos tempo no início
  • Abrimos conexões desnecessárias
Otimização de Código em Java

Inicialização preguiçosa (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;
    }
}
Otimização de Código em Java

Outro problema da nossa abordagem

// 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 ...
Otimização de Código em Java

O padrão 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 ...
}
Otimização de Código em Java

Vamos praticar!

Otimização de Código em Java

Preparing Video For Download...