"Develop a normal C# class that implements the interface you just defined".
(The fun word here is "normal".)
In overall, it's a great guideline.
Monday, February 8, 2010
Tuesday, January 5, 2010
Could not have said it better
“No one scheme of classification, more than any other, represents the real structure or order of nature. Nature indifferently submits to any and all divisions which we wish to make among existing things. Some classifications may [seem to] be more significant than others, but only by reference to our interests, not because they represent reality more accurately or adequately”.
This quote is from "Object Oriented Analysis and Design". I like the book a lot (although, it could have been shorter), and it's the best part there. If you stop to think about what it says, you will probably find that it's very true. Not only does this apply to object-oriented classification, but for any other classification or schema out there. I could talk for hours about this, but since I promised to keep everything short, I will just say: the life itself is incomprehensible.
This quote is from "Object Oriented Analysis and Design". I like the book a lot (although, it could have been shorter), and it's the best part there. If you stop to think about what it says, you will probably find that it's very true. Not only does this apply to object-oriented classification, but for any other classification or schema out there. I could talk for hours about this, but since I promised to keep everything short, I will just say: the life itself is incomprehensible.
Thursday, December 31, 2009
Short sentences as names of interfaces
I've always disliked that rule (most coding standards I saw, had such a rule) about starting names of interfaces with "I". It feels like the Hungarian notation is back. And I found myself using that leading "I" in such a way that the letter really means something. For example, instead of IInputValidator, I would create an interface named IValidateInput. This is a very reader-friendly name, in my opinion: it doesn't force you into using a word that doesn't really exist ("validator" is, obviously, a verb turned into a noun; it's not in the dictionary, according to Merriam-Webster). Also, this name explains what the implementer does, and explains in a natural way. "What is your responsibility?" - you ask the interface. "I validate input", - it replies.
Of course, all of the above applies only if the interface describes something that does one thing. In general, I prefer nouns and adjectives when naming interfaces.
Sunday, December 20, 2009
Countdown Latch, take #1
OK, enough ranting. It's time to post something useful. Here is a Countdown Latch I wrote some time ago. A countdown latch is a thread-safe object that has a counter associated with it. The latch allows threads to block until that counter -- you can only decrement the counter -- reaches zero. I always missed it in .Net FW, and one is going to be in FW 4 -- finally!
(UPDATE: of course, only after writing this I've discovered an easier solution -- one using Monitor.Wait() and Monitory.PulseAll()).
Here is the listing:
(UPDATE: of course, only after writing this I've discovered an easier solution -- one using Monitor.Wait() and Monitory.PulseAll()).
Here is the listing:
using System;
using System.Globalization;
using System.Threading;
namespace Primitives.Threading
{
///
/// A thread-safe counter (goes only down) that is capable
/// of blocking threads until the counter's value reaches zero.
///
public class CountdownLatch : IDisposable
{
private int currentCount;
private ManualResetEvent countHasReachedZero = new ManualResetEvent(false);
private object disposalCriticalSection = new object();
private ManualResetEvent allWaitingThreadsAreGone;
private const int MaximumNumberOfWaiters = int.MaxValue - 1;
///
/// Note: it's safe to access/manipulate the value of this
/// field only under a lock for disposalCriticalSection,
/// or using the Inrerlocked methods.
///
private int numberOfWaitingThreads;
private bool disposed;
public CountdownLatch(int initialCount)
{
if (initialCount <= 0)
throw new ArgumentOutOfRangeException(
"initialCount",
"Must be greater than zero.");
this.currentCount = initialCount;
}
///
/// Decreases the latch' counter value by one.
/// Does not throw, if the count has already reached zero.
///
///
public void Decrement()
{
lock (this.disposalCriticalSection)
{
this.MakeSureTheLatchHasNotBeenDisposed();
if (this.currentCount > 0)
{
this.currentCount--;
if (this.currentCount == 0)
{
this.countHasReachedZero.Set();
}
}
}
}
///
/// Current latch counter value.
/// This is for informational purposes only.
///
public int CurrentCount
{
get
{
return Thread.VolatileRead(ref this.currentCount);
}
}
///
/// Blocks the calling thread until the latch count becomes zero.
///
///
///
public void WaitUntilCountIsZero()
{
lock (this.disposalCriticalSection)
{
this.MakeSureTheLatchHasNotBeenDisposed();
this.IncrementNumberOfWaiters();
}
try
{
this.countHasReachedZero.WaitOne();
this.ThrowIfHandleHasBeenSetByDispose();
}
finally
{
this.DecrementNumberOfWaitersSignalingTheHandleIfDisposing();
}
}
///
/// This is an insane precaution: even having that many threads is simply impossible.
///
///
private void IncrementNumberOfWaiters()
{
this.numberOfWaitingThreads++;
if (this.numberOfWaitingThreads == MaximumNumberOfWaiters)
{
this.numberOfWaitingThreads--;
throw new InvalidOperationException(
String.Format(
"Cannot block - only as many as {0} waiting threads are supported.",
MaximumNumberOfWaiters));
}
}
private void DecrementNumberOfWaitersSignalingTheHandleIfDisposing()
{
lock (this.disposalCriticalSection)
{
this.numberOfWaitingThreads--;
if (this.disposed && (this.numberOfWaitingThreads == 0))
{
this.allWaitingThreadsAreGone.Set();
}
}
}
///
/// Blocks the calling thread until the latch' counter value
/// is zero or specified amount of time passes.
///
/// Amount of time to wait for latch'
/// counter value to reach zero.
/// True, if the latch has signaled (counter reached zero)
/// before specified Time Span elapsed; False, otherwise.
///
///
///
public bool WaitUntilCountIsZero(TimeSpan waitTimeSpan)
{
lock (this.disposalCriticalSection)
{
this.MakeSureTheLatchHasNotBeenDisposed();
if (waitTimeSpan < TimeSpan.Zero)
throw new ArgumentOutOfRangeException(
"waitTimeSpan",
"Must be greater than TimeSpan.Zero.");
this.IncrementNumberOfWaiters();
}
try
{
bool gotZero = this.countHasReachedZero.WaitOne(waitTimeSpan);
if (gotZero)
{
this.ThrowIfHandleHasBeenSetByDispose();
}
return gotZero;
}
finally
{
this.DecrementNumberOfWaitersSignalingTheHandleIfDisposing();
}
}
private void ThrowIfHandleHasBeenSetByDispose()
{
lock (this.disposalCriticalSection)
{
if (this.disposed && (this.currentCount != 0))
throw new ObjectDisposedException(this.GetType().FullName);
}
}
///
/// Disposes of all unmanaged resources allocated by the latch.
/// (The kernel objects used, are released).
/// Also: releases all waiting threads.
///
public void Dispose()
{
bool needToWaitForWaitersToFallOff = false;
lock (this.disposalCriticalSection)
{
if (this.disposed)
return;
this.countHasReachedZero.Set();
this.disposed = true;
if (this.numberOfWaitingThreads > 0)
{
this.allWaitingThreadsAreGone = new ManualResetEvent(false);
needToWaitForWaitersToFallOff = true;
}
}
if (needToWaitForWaitersToFallOff)
{
this.allWaitingThreadsAreGone.WaitOne();
this.allWaitingThreadsAreGone.Close();
}
this.countHasReachedZero.Close();
}
private void MakeSureTheLatchHasNotBeenDisposed()
{
if (this.disposed)
throw new ObjectDisposedException(this.GetType().FullName);
}
}
}
Monday, August 10, 2009
FIFO, fairness and synchronization primitives
Recently I ran a few multithreaded tests to figure out whether FIFO principle (First In, First Out) is respected for ManualResetEvent, AutoResetEvent, ReaderWriterLockSlim or the Monitor. I'm glad to report: all those nice things mentioned above do not support FIFO.
Why bother with FIFO in the first place? Well, it's a question of fairness: say you have a ReaderWriterLockSlim (or any other primitive from the list above) along with 2 writers waiting for a lock, one of them has been waiting for a minute and a half, and the other one has been waiting for only 2 seconds -- are they really equal like ReaderWriterLockSlim assumes, or are they not? I think, in the scenario described, we should favor the writer that started waiting earlier. You can use queues to achieve just that (at least this is what I did). This applies to any synchronization primitive.
Monitor seems to be the nicest of all four: it behaves perfectly well in terms of FIFO on a single-CPU, single-core PC. However, this is not the case with Quad-core processors, for instance.
Why bother with FIFO in the first place? Well, it's a question of fairness: say you have a ReaderWriterLockSlim (or any other primitive from the list above) along with 2 writers waiting for a lock, one of them has been waiting for a minute and a half, and the other one has been waiting for only 2 seconds -- are they really equal like ReaderWriterLockSlim assumes, or are they not? I think, in the scenario described, we should favor the writer that started waiting earlier. You can use queues to achieve just that (at least this is what I did). This applies to any synchronization primitive.
Monitor seems to be the nicest of all four: it behaves perfectly well in terms of FIFO on a single-CPU, single-core PC. However, this is not the case with Quad-core processors, for instance.
Wednesday, July 29, 2009
Moving in
This is my first entry here. I've just moved from http://idontwasteink.spaces.live.com/blog/ with all my entries.
Wednesday, July 15, 2009
Best class' description of all time
ConfigurationErrorsException class (.Net Framework) is described precisely this way: "The current value is not one of the EnableSessionState values".
Very informative, to say the least. I think it's worth noting that this class is also not a Godzilla and not a Popsicle.
Of course, we all make mistakes (I personally make dozens of them every day, and if it wasn't for TDD...), I'm just trying to stress the same old point: do not cipher your code, it's hard enough to read as it is. And misleading class' description can be nasty (although it's way worse to cipher names of classes).
Subscribe to:
Posts (Atom)