Mrinal Kamboj
Mrinal Kamboj

Reputation: 11480

Modification to Lazy<T> singleton code

Create the singleton class based on 6th version provided in Jon Skeet's book check here.

Class - CacheSingleton

public sealed class CacheSingleton<TK,TV>
    {
        private static readonly Lazy<ICache<TK,TV>> lazyIgnite =
                                                new Lazy<ICache<TK,TV>>(() =>
                                                {
                                                    NearCacheConfiguration nearCacheConfig = new NearCacheConfiguration { NearStartSize = 10240000 };

                                                    var nearCache = IgniteInstance.GetOrCreateNearCache<TK, TV>(SingletonCacheName,nearCacheConfig);

                                                    return nearCache;
                                                });

        /// <summary>
        /// 
        /// </summary>
        private static string SingletonCacheName = string.Empty;

        /// <summary>
        /// 
        /// </summary>
        public static ICache<TK, TV> Instance(string cacheName)
        {
            SingletonCacheName = cacheName;
            return lazyIgnite.Value;
        }

        /// <summary>
        /// 
        /// </summary>
        private CacheSingleton() { }
    }

Modification to the original Article:

Issues:

Any pointer to factor in the string input, along with TK,TV

Upvotes: 1

Views: 299

Answers (2)

haindl
haindl

Reputation: 3221

What about using a ConcurrentDictionary?

public static class CacheSingleton<TK, TV>
{
    private static readonly ConcurrentDictionary<string, ICache<TK, TV>> lazyIgnite = new ConcurrentDictionary<string, ICache<TK, TV>>();

    public static ICache<TK, TV> GetInstance(string cacheName)
    {
        return lazyIgnite.GetOrAdd(cacheName, name =>
        {
            NearCacheConfiguration nearCacheConfig = new NearCacheConfiguration { NearStartSize = 10240000 };
            var nearCache = IgniteInstance.GetOrCreateNearCache<TK, TV>(name, nearCacheConfig);
            return nearCache;
        });
    }
}

This is a lazy and thread-safe cache for your instances. Perhaps you also want to implement a Clear method to reset the cache.

Upvotes: 3

Matthew Watson
Matthew Watson

Reputation: 109567

Couldn't you use a ConcurrentDictionary to implement this? Something like:

public static class CacheSingleton<TK, TV>
{
    public static ICache<TK, TV> Instance(string cacheName)
    {
        return _cache.GetOrAdd(cacheName, create);
    }

    static ICache<TK, TV> create(string cacheName)
    {
        // Code to create an ICache<TK, TV> given cacheName.

        return null; // Stubbed.
    }

    static readonly ConcurrentDictionary<string, ICache<TK, TV>> _cache = new ConcurrentDictionary<string, ICache<TK, TV>>();
}

Upvotes: 2

Related Questions