遅延初期化とシングルトンパターン

Java におけるコードの最適化

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

Redis キャッシュクライアントの構築

  • Redis にアクセスするキャッシュクライアントを構築しているとします
  • この Redis クライアントはサードパーティのプロバイダーでホストされています
  • クライアントへの接続にはネットワーク呼び出しが必要で、500ms かかるとします

$$

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...