Archive for August 9, 2008

Weak References

Posted: August 9, 2008 in .NET, CLR
Tags: ,

Last sunday we had a session on .NET Internals as part of the monthly session of Kolkata .NET User group.The session went very well.But the discussion on what exactly happens for GC of a WeakReference class remained open ended.After going through Jeffrey Richters book “CLR via C#” I found lot of information on how the WeakReference class works.
For every app domain CLR maintains a table called GC Handle table.This table can be accessed via the System.Runtime.InteropServices.GCHandle class.Along with GCHandle there is an enumeration called GCHandleType which needs to be passed to the Alloc method of GCHandle class
The four values of this enumeration are:
1)Weak – This handle type is used to track an object, but allow it to be collected. When an object is collected, the contents of the GCHandle are zeroed. Weak references are zeroed before the finalizer runs.
 
2)WeakTrackResurrection-This handle type is similar to Weak, but the handle is not zeroed if the object is resurrected during finalization.

3)Normal-This handle type is used to track an object and prevent its collection by the garbage collector. This enumeration member is useful when an unmanaged client holds the only reference, which is undetectable from the garbage collector, to a managed object.

4)Pinned-This handle type is similar to Normal, but allows the address of the pinned object to be taken. This prevents the garbage collector from moving the object i.e. perform compaction.

WeakReference class is wrapper around GCHandle class with the GCHandleType –  Weak and WeakTrackResurrection.WeakReference constructor calls to GCHandle’s Alloc method and Target is same as the Target property of GCHandle class.

One of the overloaded constructor of this class is WeakReference(Object, Boolean).The boolean parameter if false then it is called a short weak reference otherwise a long weak reference.By default it is always short weak reference.

Short Weak Reference

The target of a short weak reference becomes null when the object is reclaimed by garbage collection.(Weak)

Long Weak Reference

A long weak reference is retained after the object’s Finalize method has been called. This allows the object to be recreated, but the state of the object remains unpredictable.(WeakTrackResurrection)

The GC in the marking phase also scans this GC Handle table to identify the object is reachable/unreachable.

As per MSDN Guidelines for Using Weak References are

 Use long weak references only when necessary as the state of the object is unpredictable after finalization.

 Avoid using weak references to small objects because the pointer itself may be as large or larger.

 Avoid using weak references as an automatic solution to memory management problems. Instead, develop an effective caching policy for handling your  application’s objects.
 

I found a very good suggesstion in Jeffrey Richters book in this regard.GC does not occur when the memory is full but occurs when the Generation 0  becomes full which is after 256 KB of memory allocation.So using WeakReference might lead to collection & re-creation of a memory intensive object  even when there is no memory crunch.This can result in significant performance hit.So while using WeakReference for caching scenario we have to  strike a balance between memory usage and appliaction performance.The caching algorithm needs to be designed with care and adhoc usage of  WeakReference will not solve the problem.

In my last post I had discussed about the basics of transactions,transaction manager & resource manager.In this post we will discuss about the Lightweight Transaction Manager(LTM) a transaction manager introduced with .NET 2.0.
Prior to LTM the only transaction manager available in the Microsoft world was the Micrsoft Distributed Transaction Coordinator(MSDTC).This transaction manager is able to handle transaction flowing across process/machine/network boundaries.But MSDTC has it’s own overheads and which is not required for simple transactional scenarios.That’s why the LTM was introduced.
LTM can manage transactions with
a) Any number of volatile resource managers
b) Single durable resource manager
c) No flows across process/machine
When anyone of the above mentioned conditions is violated the transaction gets promoted/escalated to the MSDTC or Kernel Transaction Manager(introduced with Windows Vista)
One of the great features of LTM is management of volatile or in-memory resource managers.Using the classes/interfaces present in System.Transaction namespace we can make Plain old .NET Objects transaction aware.

The first important class to take note of is the Transaction.It contains methods used for implementing resource managers for enlistment. It also provides functionalities for cloning a transaction and controlling the current transaction context. We can get current transaction, if one is set, using the static Current property.
      tx = Transaction.Current;
            if (tx != null)
            {
               ….
            }
As we have seen in the earlier post transaction manager communicates with the resource managers.Each resource manager needs to enlist with the transaction manager for a particular transaction.For this the Transaction class provides two methods EnlistVolatile-for volatile resource managers and EnlistDurable for durable resource managers.
For custom resource managers to enlist in the transaction they have to implement the IEnlistmentNotification interface.This interface defines the contract that a resource manager should implement to provide two phase commit notification callbacks for the transaction manager upon enlisting for participation.
This interface specifies the following methods:
      
 This callback is invoked during the second phase of a transaction if the transaction is commited.
        public void Commit(Enlistment enlistment)
        {
            ….
        }
 This callback is invoked during the second phase of a transaction if the transaction is in doubt.
        public void InDoubt(Enlistment enlistment)
        {
            …
.
        }
 This notification method is invoked in the first phase when the transaction manager asks participants whether they can commit the transaction.

        public void Prepare(PreparingEnlistment preparingEnlistment)
        {
            …
        }
 This callback is invoked during the second phase of a transaction if the transaction is aborted.
        public void Rollback(Enlistment enlistment)
        {
           …
        }

    }
Another important class in TransactionScope.This class is used for marking a code block transactional.On instanting the TransactionScope the transaction manager which transaction to participate.This is guided by the TransactionScopeOption parameter.The ambient transaction is the transaction in whichcode executes.A reference to the ambient transaction can be obtained by Current property of the Transaction class.
If no exception occurs within the transaction scope (that is, between the initialization of the TransactionScope object and the calling of its Dispose method), then the transaction in which the scope participates is allowed to proceed. If an exception does occur within the transaction scope, the transaction in which it participates will be rolled back.When code completes all tasks the Complete method has to be called to inform that transaction manager that it is acceptable to commit the transaction. If this method is not called then transaction is aborted.

The following classes shows the sample and simple implementation of a transaction aware Hashtable:

   class TransactionHashtable
    {
        private Hashtable ht = null;
        private Transaction tx;
        private bool enListed = false;
        public TransactionHashtable()
        {
            ht = new Hashtable();
        }
        public void Add(object key, object value)
        {
            tx = Transaction.Current;
            if (tx != null)
            {
                if (!enListed)
                {
                    tx.EnlistVolatile(new HashtableEnlistor(ref ht), EnlistmentOptions.None);
                    enListed = true;
                }
            }
          
            ht.Add(key, value);
        }
        public IDictionaryEnumerator GetEnumerator()
        {
            return ht.GetEnumerator();
        }
    }

    class HashtableEnlistor : IEnlistmentNotification
    {
        Hashtable ht = null;
        Hashtable htOld = null;
        public HashtableEnlistor(ref Hashtable ht)
        {
            this.ht = ht;
            MemoryStream ms = new MemoryStream();
           
            IFormatter f = new BinaryFormatter();
            f.Serialize(ms, ht);
            ms.Position = 0;
            htOld = (Hashtable)f.Deserialize(ms);
        }
        #region IEnlistmentNotification Members

        public void Commit(Enlistment enlistment)
        {
            enlistment.Done();
        }

        public void InDoubt(Enlistment enlistment)
        {
            throw new NotImplementedException();
        }

        public void Prepare(PreparingEnlistment preparingEnlistment)
        {
            preparingEnlistment.Prepared();
        }

        public void Rollback(Enlistment enlistment)
        {
            ht.Clear();
            IDictionaryEnumerator en = htOld.GetEnumerator();
            while (en.MoveNext())
            {
                ht.Add(en.Key,en.Value);
            }
            enlistment.Done();
        }

        #endregion
    }