Archive for April 10th, 2008
Tata Nano vs electric cars
Ricardo Parker, over at SeattlePI, while talking about Tata Nano said, “I’m sure Indians would much rather run on electricity than gasoline if the cost of the cars was the same”. While I’m sure his post is full of material to attract wonderful comments from Indian readers in any case, I thought I’ll add something on my blog to make my point amidst the noise that’s likely to ensue over there.
The market segment that Tata Nano is targeted at, in my opinion, cares about cost more than anything else. Tata is a household name in India and I doubt there would be a house that didn’t have something manufactured by Tata. They are into pretty much everything you can think of – from energy production to IT. That leads to a strong perception of reliability in people’s minds when consuming goods made by Tata. Ricardo mentioned about a new electric car being introduced as competition to Nano. A new entrant wouldn’t necessarily be able to match them in terms of auto service centers and other support related things immediately so Tata will definitely win in the short term with Nano.
That being said, it would be interesting to see how the auto-sector changes in India as a result of Tata Nano in 5 years from now.
Link to Tata Group on Wikipedia.
Order of keys in Dictionary (.NET 2.0)
Problem:
What is the output of the following piece of code going to be?
Dictionary dict = new Dictionary();
dict.Add("ddd", "ddd");
dict.Add("bbb", "bbb");
dict.Add("ccc", "ccc");
dict.Add("aaa", "aaa");
StringBuilder output = new StringBuilder();
foreach (string key in dict.Keys)
{
output.Append(key);
output.Append(" ");
}
MessageBox.Show(output.ToString());
Solution:
There are 24 ways of arranging 4 items (4! – four factorial). However the output in this case is going to be “ddd bbb ccc aaa”. Try adding a different set of keys and the keys will still be available in the Keys collection of Dictionary in the same order as the one in which you added the keys and values.
So can we rely on the order of keys in our code, and why is that happening to begin with?
According to MSDN:
The order of the keys in the Dictionary<(Of <(TKey, TValue>)>)..::.KeyCollection is unspecified, but it is the same order as the associated values in the Dictionary<(Of <(TKey, TValue>)>)..::.ValueCollection returned by the Values property.
So the short answer to the previous question is “Nope”.
To get an understanding of how hash-tables and dictionaries work in general, you can read the Wikipedia article about hash-tables. However to give a brief description, Dictionary class is implemented in .NET 2.0 by using an array of buckets. Each key is mapped to a unique bucket in this array. A separate array of entries is maintained. Each bucket merely contains the index of the corresponding slot in the entries array that contains the key that was mapped. That slot in the entries array also contains the value associated with that key (and the hashcode too, but we don’t need to worry about it for now). The enumerator that is returned to allow enumeration of keys traverses the entries array and returns keys in the order in which they are encountered. Since items in the entries array are added in the order in which you call Add in your code, keys encountered in the “foreach” are in the same order as the one in which you added them.
Since the ordering of keys is being determined by the specific way in which Dictionary was implemented in .NET 2.0, it wouldn’t be wise to rely on it in our code. That’s what MSDN said to begin with
By the way, the stuff about entries also explains why the values are returned in the same order as keys – mentioned in the MSDN documentation. It’s because the same slot in the entries array contains the value part in addition to the key.
The description of Dictionary implementation in .NET 2.0 was based on my reading of Dictionary.cs released along with the rest of .NET framework 2.0 code to everyone by Microsoft.
The empty try block mystery
Problem:
I had used .NET Mass Downloader tool to download .NET 2.0 Framework sourcecode some time ago. While reading Timer.cs (System.Windows.Forms.Timer) and a couple of other classes I noticed something interesting.
Does the following piece of code look odd to you? Notice the empty “try” block and all processing being done in the “finally” block.
public void Foo()
{
try
{
}
finally
{
DoSomething();
DoSomethingElse();
}
}
It’s (most likely, you’d think - right?) not the work of a programmer misunderstanding what was asked of him
Solution:
This methodology guards against a Thread.Abort call interrupting the processing. The MSDN page of Thread.Abort says that “Unexecuted finally blocks are executed before the thread is aborted”. So in order to guarantee that your processing finishes even if your thread is aborted in the middle by someone calling Abort on your thread, you can place all your code in the finally block (the alternative is to write code in the “catch” block to determine where you were before “try” was interrupted by Abort and proceed from there if you want to).
But what if your thread is aborted while code in the finally block is executing?
Again, here’s what the MSDN page says:
“In the .NET Framework versions 1.0 and 1.1, there is a chance the thread could abort while a finally block is running, in which case the finally block is aborted.“
That’s bad because this behavior could potentially cause leakage of resources if you have your code for freeing up resources written in the “finally” block and it got interrupted in the middle by a call to Abort.
What about .NET 2.0:
I wrote a simple program to check the behavior and on my machine running .NET 2.0 on Vista Enterprise edition, finally block isn’t interrupted even if an Abort call is made on the thread running the “finally” block.
The Code:
I had a function named LaunchThread to start the thread. This function was called from the handler for the “Load” event of the form.
private Thread mThread;
public void LaunchThread()
{
this.mThread = new Thread(ThreadMain);
this.mThread.Start();
}
I had a button on my form. I had a handler for its Click event which basically called Abort on the thread.
private void button1_Click(object sender, EventArgs e)
{
if (this.mThread != null && this.mThread.IsAlive)
{
this.mThread.Abort();
this.mThread.Join();
MessageBox.Show("Thread Aborted");
}
else
{
MessageBox.Show("Thread already died");
}
}
This is what ThreadMain looked like:
public void ThreadMain()
{
try
{
}
finally
{
MessageBox.Show("Going to sleep!");
Thread.Sleep(10000);
MessageBox.Show("Just finished sleeping!");
}
}
To test the application, I ran the application, waited a couple of seconds and then clicked on the button. Here is the sequence of messages that appeared:
- As soon as the form was launched – “Going to sleep!
- No messages appeared in response to me clicking on the button.
- After 10 seconds – “Just finished sleeping!”
- And immediately after that – “Thread Aborted”
Since no message appeared in response to me clicking on the button, it is clear that Thread.Sleep call in the “finally” block was not interrupted by Abort.
Changing ThreadMain like the following, leads to different results:
public void ThreadMain()
{
try
{
MessageBox.Show("Going to sleep!");
Thread.Sleep(10000);
MessageBox.Show("Just finished sleeping!");
}
finally
{
}
}
In this case, when I clicked on the button, Thread.Sleep call was interrupted by the call to Abort as I saw the following messages:
- As soon as the form was launched – “Going to sleep!”
- Just after clicking on the button “Thread aborted”