Khởi tạo lười biếng và mẫu singleton

Tối ưu hóa mã trong Java

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

Xây dựng client cache Redis

  • Hãy tưởng tượng ta xây dựng client cache kết nối Redis
  • Client Redis đặt tại nhà cung cấp bên thứ ba
  • Thiết lập kết nối cần gọi mạng — giả sử mất 500ms

$$

Gọi qua mạng để thiết lập kết nối Redis

Tối ưu hóa mã trong Java

Triển khai đơn giản (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");
    }
}
  • Khởi tạo (eager) kết nối Redis
Tối ưu hóa mã trong Java

Vấn đề tiềm ẩn với cách tiếp cận này

Cách này đơn giản và chạy được, nhưng có một vấn đề tiềm ẩn

Nếu ta không cần client Redis thì sao?

  • Lãng phí thời gian khởi động
  • Tạo kết nối không cần thiết
Tối ưu hóa mã trong Java

Khởi tạo lười biếng

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;
    }
}
Tối ưu hóa mã trong Java

Một vấn đề khác với cách tiếp cận của ta

// 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 ...
Tối ưu hóa mã trong Java

Mẫu 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 ...
}
Tối ưu hóa mã trong Java

Let's practice!

Tối ưu hóa mã trong Java

Preparing Video For Download...