Saturday, April 17, 2010

Structural Patterns - Adapter Pattern

Design Patterns help to make a system independent of how its objects are created, composed, and represented. These patterns become important when emphasis shifts away from
Hard-Coding a fixed set of behaviours toward defining a
smaller set of fundamental behaviours that can be composed in to any number of more complex ones. [GOF]

Pattern which defines the composition of classes and objects in the system to build the desired structure is known as Structural Pattern. Structural patterns define a way to combine two or more independent developed libraries. Developed libraries may differ in their implementation but can work for each other to produce the desired result without knowing the internal details.

For example, a particular Car model can make use of the cooling system to provide A/C feature though the cooling system is developed independent of the Car model.

One example of the structural pattern is Adapter pattern. Adapter pattern promotes the development of one interface to a particular implementation in order to provide uniform abstraction of different interfaces. Adapter pattern is particularly useful when you have two different classes with incompatible interfaces.

There are 3 entities to participate in the Adapter pattern. If a class wants to make use of an implementation, then these classes can be named as Target and Adaptee, respectively. The wrapper which provides the requested operations by the target using the implementation of the Adaptee is called Adapter. Below is the interaction diagram between Target, Adapter and Adaptee.


Implementation

Let’s take the example of Stack implementation.

Suppose Stack interface is exposed to the client to support stack data structure and operations. Now, there is a need to implement the Generic stack data structure. One possible approach is to use generic dictionary to implement generic stack. Generic dictionary is the class implemented in library to support generic and retrieval and storage of the items.

We can classify stack interface exposed to the client as Target and Dictionary class as an Adaptee. Create a wrapper class (GenericStack) which takes the responsibility to implement the stack operations using dictionary class. One of the possible implementation will follow the structure shown in the below image.


Code:

Stack Interface



internal


interface


IStack


where
T :

IComparable



{

///

/// To Push Item in the Stack

///

void Push(T item);

///

/// Pop up the given item from the Stack

///

T Pop();


/// To Pop up the item from the Stack

T[] Pop(T item);

}

}



Generic Stack


/// This class defines Generic Stack.

class

GenericStack
:

IStack

where T :

IComparable

{

#region Fields


private

Dictionary
<int, T> dicStackItemCollection;



private


Dictionary
<int,

int
> dicItemKeyCollection;



int
iItemcount;



#endregion
Fields



#region
Properties



#endregion
Properties



#region
Methods



public
GenericStack()



{



iItemcount = 0;



}



///



///
To Push Item in the Stack



///



///



public


void
Push(T item)



{



// Initialize Stack Item Collection - Deferred initialization



if
(dicStackItemCollection ==

null
)



{



dicStackItemCollection =

new


Dictionary
<int, T>();



dicItemKeyCollection =

new


Dictionary
<int,

int
>();



}



// Do Not Add Null items



if
(item !=

null
)



{



dicStackItemCollection[iItemcount++] = item;



dicItemKeyCollection[item.GetHashCode()] = iItemcount;

}

}

///



///
To Pop up the item from the Stack

public T Pop()



{



// Set Item to Its default value



T item =

default
(T);



// If Item exists, pop



if
(iItemcount > 0)



{



item = dicStackItemCollection[iItemcount - 1];



dicStackItemCollection.Remove(iItemcount - 1);



iItemcount--;



}



return
item;



}



///



///
Pop up the given item from the Stack



///
Returns all removed items from the stack.



///



///



///



public
T[] Pop(T item)



{



T[] items =

null
;



int
itemKey;



// If Item exists, pop



if
(iItemcount > 0 && IsItemExists(item,

out
itemKey))



{



items =

new
T[itemKey - 1];



while
(itemKey > 0)



{



// Get the Item from the Collection before removing it



items[itemKey - 1] = dicStackItemCollection[itemKey];



// Remove item from the Collection



dicStackItemCollection.Remove(itemKey--);



}



iItemcount = dicStackItemCollection.Count + 1;



}



return
items;



}



///



///
To Get the Item from the collection



///



private


bool
IsItemExists(T item,

out


int
itemKey)



{



itemKey = -1;



if
(dicItemKeyCollection.ContainsKey(item.GetHashCode()))



{



itemKey = dicItemKeyCollection[item.GetHashCode()];



}



return
itemKey != -1;



}

#endregion Methods

}



Client:



class


Client

{

#region Fields

private

IStack
<int> stack;

#endregion Fields

#region Properties

#endregion Properties

#region Methods

public Client(IStack<int> stack)

{

this.stack = stack;

}

///

/// To Simulate Operations on Stack

///

internal

void
DoSomeOperartions()

{

int item;

Console.WriteLine("Push: 5");

stack.Push(5);

Console.WriteLine("Push: 4");

stack.Push(4);

item = stack.Pop();

Console.WriteLine("Pop: " + item);

Console.WriteLine("Push: 3");

stack.Push(3);

item = stack.Pop();

Console.WriteLine("Pop: " + item);

item = stack.Pop();

Console.WriteLine("Pop: " + item);

item = stack.Pop();

Console.WriteLine("Pop: " + item);

}

#endregion Methods

}



Main Method:


class

Program

{

static

void
Main(string[] args)

{

IStack<int> stack =


new


GenericStack
<int>();


// Set Stack to the Client



Client
<int> client =

new


Client
<int>(stack);



// Ask client to do some operations



client.DoSomeOperartions();



Console
.ReadLine();

}

}


** Please note that above implementation relies on the Hash code of the object in the stack. Results may be unpredictable if GetHashCode() method has been overridden in object’s type.

Monday, April 5, 2010

Understanding Pointers with inner wears :)

It was the summer of 2007 when I was waiting for the Joining dates of Infosys Technologies (I waited till winterJ). During those days, I used to visit some C language communities on Orkut. One day I saw a very interesting discussion about the pointers in C.

One guy asked a question in the C community:

Why can't an integer pointer point to a floating number????

Immediately after this, there was another question commeting to the above question:

Why can't boys wear bra and panties????

Some supported this comment and some gave nice replies to the actual question. Here is what I replied to the post….

-------------------------------------------------------------------------------------------------------------------

“Any pointer type always points to a single byte.... and that byte is always the starting byte of the variable...
if a variable is a pointer, it will store the address of the first byte of the variable only.

So, you can store the address of the any type of the variable to the any type of the pointer.......
now the question arises... THEN WY DIFFERENT TYPES Of POINTERS......

By making a type of pointer ... it tells the compiler that how many bytes a processor will process wen it will encounter the pointer.
In dos environment...
If integer pointer..... will process two bytes simultaneously.
If float pointer..... Will process 4 bytes.

And it also tells to the compiler that on increment..... Which byte will be the next address.
i.e. if float pointer is ptrf, then ptrf++ will jump on the 5th next byte.

----------------------------------------------
so...... store anyone, anywhere... But don’t put your expectations.......
in a nutshell......
"boys can wear panties and bra..... But don’t expect them to behave like a girl"

-------------------------------------------------------------------------------------------------------------------

Though the discussion was really good but what I remember even today is the last line of my replyJ. And so the subject line of the blog.

Saturday, April 3, 2010

Multithreading - Task Synchronization - Barrier Class - C# 4.0

4.0 release has lots of stuff for multithreading. One of them is the Barrier class focused towards the synchronization of the tasks. This class is placed in the namespace System.Threading (System.dll).
Formally, this class enables multiple tasks to cooperatively work on an algorithm in parallel through multiple phases. A Barrier enforces the stopping of execution between a number of threads preventing further execution until all threads have reached the given point. On other way, all threads may start their work independently but can not proceed beyond a certain point of time until other threads have not reached to that point.
This class reminds me the typical college trips (i.e. Trip will start from point X and everyone should meet at point X). Let’s see how this class achieve the stated functionality.
Assume there are 3 friends Tom, Tomm and Tommm (feel free to change ). On Friday night, they decided to go for a trip. So, they decided that we will meet at the Trip centre to enter the new city. To simplify the scenario, let’s assume either all 3 will go for the Trip or they will cancel the Trip. So, they registered their trip with the centre. Trip canter is responsible to tell the exact position of the trip members and give a signal to start or cancel the Trip.
So, here is your Trip centre and its token (say registration token):
static Barrier tripCenter;
static CancellationToken token;


Now, here is how registration will happen:
// Register 3 members to the Barrier
tripCenter = new Barrier(3);

Before we proceed further on Trip, let’s see what else this Barrier class has to offer during the registration:
1. Class offers the flexibility to increase or decrease the number of participants at any point of time after the registration process.
// Changed the plan. Let's make it five participants.
tripCenter.AddParticipants(2);

// 5th Person is in trouble and he is not joining us. Settle on 4.
tripCenter.RemoveParticipant();

2. You can ask for the notification once everyone has reached at the barrier. You can provide the Action at the time of registration. Here is what we will define for this trip
tripCenter = new Barrier(3, (barrier) =>
{
Console.WriteLine("Every One has Arrived. All of you [Total - {0} ] can proceed for your Trip now. My duty for phase {1} is over. Cheers.", barrier.ParticipantCount, barrier.CurrentPhaseNumber);
});


Next step is to provide the task to be executed by the participants before reaching at the barrier. This task is the set of actions performed by your workers (or threads). Here we go for the task:
static void MakeMyTrip(string name, TimeSpan timeToReachPetrolPump)
{
try
{
Console.WriteLine("[{0}] Leaving House", name);

// Perform some work
Thread.Sleep(timeToReachPetrolPump);
Console.WriteLine("[{0}] Arrived at Petrol Pump", name);

// Need to sync here
tripCenter.SignalAndWait(token);

// Perform some more work
Console.WriteLine("[{0}] Starting the Trip Now", name);
}
catch (OperationCanceledException)
{

Console.WriteLine("[{0}] Problem in Bike... Trip Cancelled!! Going
home!", name);
}
}

Let’s assume that things will go fine for this trip and ignore the Catch block for a while. We will discuss it shortly. As per the task:
1. Participant will leave the house and will reach at petrol pump.
2. Once they have reached at the Trip centre, they need to signal this event to barrier. (Inform Trip Centre that you have arrived).
3. No one can proceed further without the signal from the barrier.
4. How Barrier maintains this data is with every call to SignalAndWait(), the number of signals received by the barrier is incremented. Once the number of signals received reaches the number of participants the Barrier was constructed with, all threads are then allowed to continue execution.
And, the last step is to Activate your participant for the Trip.

var tom = new Thread(() => MakeMyTrip("tom", TimeSpan.FromSeconds(0)));
tom.Start();

var tomm = new Thread(() => MakeMyTrip("tomm", TimeSpan.FromSeconds(4)));
tomm.Start();

var tommm = new Thread(() => MakeMyTrip("tommm", TimeSpan.FromSeconds(6))); tommm.Start();

// Allow them to complete their trip
tom.Join();
tomm.Join();
tommm.Join();

If you will execute this program, you will observe that participants are leaving the home and reaching at the petrol pump in random order. But no one is allowed to proceed beyond the barrier until all participants are not ready. This class provides a god help otherwise we would have written code with Events (which involves manual intervention for the synchronization).
So far things are good as we assumed that there won’t be any problem to anyone and everyone will reach at the barrier. This is something not practical. There may be several scenarios when thread or worker may stop it’s execution (say data fault). In this case, worker may inform the other worker threads (participants in our case) about the cancellation of the Trip. And therefore, above untouched Catch block comes into the picture.
In the beginning, we have declared Barrier class reference along with reference of the class CancellationToken. This class provides the cancellation token for the given Barrier.

var source = new CancellationTokenSource();

// Get the Token
token = source.Token;

// Activate the Worker Threads

// Not Happy with the Idea, Cancel the Trip
source.Cancel();

Once the source has raised the alarm for cancel, OperationCanceledException exception will be raised to all waiting worker threads.

Finally, the action defined for the barrier. Once all participants have reached to the barrier, barrier will execute the action defined at the time of registration. In our, there is an announcement by the Trip Centre. This action will not be executed by the barrier if the Source has aborted the task (say when Trip is cancelled, there will be no announcement).

You saw that how we can use barrier for the synchronization of the tasks. But there are several other aspects which can be discussed here:
1. What will happen if any worker of the barrier has been aborted without any notice?
2. Will other threads throw time out exception or will wait indefinitely.
3. Can we define any time limit on each worker to reach at barrier?
I will keep these questions open for the discussion.