लेज़ी इनिशियलाइज़ेशन और सिंगलटन पैटर्न्स

Java में कोड ऑप्टिमाइज़ करना

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

Redis कैश क्लाइंट बनाना

  • मान लीजिए हम Redis{{1}} को हिट करने वाला कैश क्लाइंट बना रहे हैं
  • हमारा 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...