Blog de Francisco Velázquez

otro blog personal

Simple cache para BusinessObjects

leave a comment »

Debido a la naturaleza de mi trabajo, aplicaciones multitenant, y servicios M2M, para mejorar el rendimiento suelo cachear muchos objectos que tienen un tasa de lectura muy alta y de cambios muy muy pequeño. Así que para facilitar el trabajo, me he decido crear una pequeña utilidad.

    /// <summary>
    /// Concurrent cache for BusinessObject.  It doesn´t clean cache, useful for small data.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BusinessObjectCache<T>
        where T : BusinessObject<T>
    {
        static ReaderWriterLockSlim Locker = new ReaderWriterLockSlim();
        static volatile Dictionary<object, T> storage;

        static BusinessObjectCache()
        {
            Locker.EnterWriteLock();
            try
            {
                storage = new Dictionary<object, T>();
            }
            finally { Locker.ExitWriteLock(); }
        }

        public T Get(object id)
        {
            T o = null;
            Locker.EnterReadLock();
            try
            {
                if (storage.ContainsKey(id))
                {
                    o = storage[id];
                    return o;
                }
            }
            finally { Locker.ExitReadLock(); }

            if (o == null)
            {
                Locker.EnterUpgradeableReadLock();
                try
                {
                    if (!storage.ContainsKey(id))
                        o = BusinessObject<T>.Retrieve(id);

                    if (o != null)
                    {
                        Locker.EnterWriteLock();
                        try
                        {
                            storage[id] = o;
                        }
                        finally { Locker.ExitWriteLock(); }
                    }
                }
                finally { Locker.ExitUpgradeableReadLock(); }
            }

            return o;
        }
    }

A ver si me lo curro y la hago LRU.

Written by fravelgue

July 21, 2011 at 5:44 pm

Posted in development

Tagged with , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: