Ледача ініціалізація та шаблони сінглтона

Оптимізація коду в Java

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

Створення клієнта кешу Redis

  • Уявімо, що ми будуємо клієнт кешу, який звертається до Redis
  • Наш клієнт Redis розміщено у стороннього провайдера
  • Налаштування з'єднання потребує мережевого виклику — припустімо, це займає 500 мс

$$

Виклик по мережі для встановлення з'єднання з Redis

Оптимізація коду в Java

Проста (рання) реалізація

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");
    }
}
  • Рання ініціалізація з'єднання з Redis
Оптимізація коду в Java

Потенційна проблема цього підходу

Це здається простим — і працюватиме — але має потенційну проблему

А що як клієнт Redis нам узагалі не потрібен?

  • Ми даремно витратили час на старті
  • Ми встановили зайві з'єднання
Оптимізація коду в Java

Ледача ініціалізація

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;
    }
}
Оптимізація коду в Java

Ще одна проблема нашого підходу

// 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 ...
Оптимізація коду в Java

Шаблон сінглтона

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 ...
}
Оптимізація коду в Java

Давайте потренуємось!

Оптимізація коду в Java

Preparing Video For Download...