Is it likely(), or unlikely()?

30. November 2008

This post is relatively off-topic compared to my other posts on C# and .net but I see a value behind it, so decided to blog about it.

While I have been dealing with my assignment on linux system calls, I have seen something interesting. There were 2 macros in use for condition evaluation: likely(condition) or unlikely(condition). This is a compiler optimization used in linux kernel and it isn’t meant to be used in normal applications. It is even useless in ordinary applications. However, this is definitely not the case for an OS kernel where even a single instruction for performance matters.

Now, how does this work? What is the magic behind it?

When we take a look at the definition of likely and unlikely macros we see

#define likely(x) __builtin_expect((x),1)
#define unlikely(x) __builtin_expect((x),0)

I didn’t know about __builtin_expect, so I searched for it and reached that page.

It says that this call can be used to provide the compiler with branch prediction information and the compiler uses it to produce optimized assembly code. Something had appeared in my head, I wonder if there was more magic going on so I gave it a go.

int test_likely(int c)
{
    if(__builtin_expect(c,1))
    {
        c++;
    }
    else
    {
        c=1
    }
    return c;
}

This code yielded in the following assembly code

image

And for unlikely,

int test_unlikely(int c)
{
    if(__builtin_expect(c,0))
    {
        c++;
    }
    else
    {
        c=1
    }
    return c;
}

compiler produces

image

Do you see the difference? On line 13(d), we see that it executes jne or je instruction. If the condition is likely to happen, it doesn’t branch and executes the code under if, otherwise branch to else. If the condition is unlikely to happen, it keeps else close to the code, since else block is likely to be executed.

Those kind of optimizations should be used as a last resort. In most applications, you don’t even need such optimizations, you should concentrate on bottlenecks instead, such as network traffic etc.

I’d like to end this post with the quote I already said:

“We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.” (Donald Knuth)

, ,

NHibernate hbm2ddl

22. November 2008

NHibernate has a number of configuration options: Enabling statistics, Caching etc. You can check more from here

I will now talk about an unknown feature(well, at least I didn’t know until I implement SchemaValidator): hbm2ddl.auto

Hbm2ddl.auto is declarative way to use SchemaExport / SchemaUpdate / SchemaValidator (well the latter sounds odd, maybe it would be better to call it SchemaValidate, what do you think?). If you add

<property name="hbm2ddl.auto">create</property>

for example, it will run

new SchemaExport(cfg).Create(false, true);

during SessionFactory initialization, with which you probably are familiar.

There are several options for hbm2ddl.auto.

  1. update executes SchemaUpdate which will modify your existing table with new mapping, without dropping any columns.
  2. create-drop executes SchemaExport when SessionFactory initializes and drops the schema at the end of the life of the factory.
  3. validate executes SchemaValidator which I blogged about here

If you prefer not to use programatic way, configuration is just here.

kick it on DotNetKicks.com

NHibernate SchemaValidator

22. November 2008

NHibernate provides a number of tools for developers to manage their database. I prefer mapping driven approach in which I let NHibernate generate the schema for database for me. By that way, I only concentrate on my domain. For me, database is not the center but only a tool for storage most of the cases.

This approach is valid only for greenfield projects. If you’re using a legacy database, however, things get more complicated and you write your mappings according to your database.

NHibernate now(with revision 3918, which means you have to use trunk until we release it) provides a way to verify your mappings against your database.

The usage is similar to other tools

I won’t write a dedicated code for this but rather I am going to copy the tests from the code itself.

[TestFixture]
public class SchemaValidateFixture
{
    [Test]
    public void ShouldVerifySameTable()
    {
        string resource1 = "NHibernate.Test.Tools.hbm2ddl.SchemaValidator.1_Version.hbm.xml";
        Configuration v1cfg = TestConfigurationHelper.GetDefaultConfiguration();
        using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource1))
        new NHibernate.Tool.hbm2ddl.SchemaExport(v1cfg).Execute(true,true,false,true);

        var v1schemaValidator = new NHibernate.Tool.hbm2ddl.SchemaValidator((v1cfg));
        v1schemaValidator.Validate();
    }
    [Test]
    public void ShouldNotVerifyModifiedTable()
    {
        string resource1 = "NHibernate.Test.Tools.hbm2ddl.SchemaValidator.1_Version.hbm.xml";
        string resource2 = "NHibernate.Test.Tools.hbm2ddl.SchemaValidator.2_Version.hbm.xml";
        Configuration v1cfg = TestConfigurationHelper.GetDefaultConfiguration();
        Configuration v2cfg = TestConfigurationHelper.GetDefaultConfiguration();
        using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource1))
            v1cfg.AddInputStream(stream);
        using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource2))
            v2cfg.AddInputStream(stream);
        new NHibernate.Tool.hbm2ddl.SchemaExport(v1cfg).Execute(true, true, false, true);
        var v2schemaValidator = new NHibernate.Tool.hbm2ddl.SchemaValidator((v2cfg));
        try
        {
            v2schemaValidator.Validate();                
        }
        catch (HibernateException e)
        {
            Assert.That(e.Message, Text.StartsWith("Missing column: Name"));
        }
    }
}

SchemaValidator has a single method called Validate. You give it the configuration and it validates the schema.

That’s it. In the next post I’ll write about an unknown configuration option for NHibernate.

kick it on DotNetKicks.com

Castle ServiceIdResolver

19. November 2008

I like Castle, a lot. The thing that I like about it is not only its clean api&design, but also the extensibility points it has.

Sometimes, there are cases when you need to resolve a type that is not registered in the container. Such examples for those cases may be an array of all services of a specific type. An example to this can be found at hammet’s post

This post will be an answer to a question raised in the Castle Project User List.

The question is that he needs his service to be aware of his Id registered in windsor. This is possible with the use of ISubDependencyResolver. Even though this design seems violation of SoC, I believe that it will demonstrate the ISubDependencyResolver well enough.

Tests are first, here they are

public class SampleService1
{
    public SampleService1(string serviceId)
    {
        this.ServiceId = serviceId;
    }
    public string ServiceId { get; set; }
}
public class SampleService2
{
    public SampleService2(string serviceId)
    {
        this.ServiceId = serviceId;
    }
    public string ServiceId { get; set; }
}
public class SampleService3
{
    public SampleService3(int serviceId)
    {
        this.ServiceId = serviceId;
    }
    public int ServiceId { get; set; }
}
public class ServiceIdResolverTests
{
    public ServiceIdResolverTests()
    {
        this.container = new WindsorContainer();
        this.container.Kernel.Resolver.AddSubResolver(new ServiceIdResolver());
        this.container.Register(Component.For<SampleService1>().Named("service1"))
            .Register(Component.For<SampleService2>().Named("service2"))
            .Register(Component.For<SampleService3>().Named("service3"));
    }
    private readonly IWindsorContainer container;

    [Fact]
    public void CanResolveDependencyWithServiceId()
    {
        var s1 = container.Resolve<SampleService1>();
        var s2 = container.Resolve<SampleService2>();
        Assert.Equal("service1", s1.ServiceId);
        Assert.Equal("service2", s2.ServiceId);
        Assert.Throws<HandlerException>(() => container.Resolve<SampleService3>());
    }
}

Now comes to the implementation.

ISubDependencyResolver has 2 simple methods, namely CanResolve and Resolve. CanResolve tells the container that this resolver may handle the operation of resolving and resolve does the real work.

We should define a convention here, about when to resolve a dependency with the service’s id. My convention is if the parameter name is “serviceid”, then this means that the service wants to know about his id.

public class ServiceIdResolver : ISubDependencyResolver
{
    #region ISubDependencyResolver Members
    public bool CanResolve(CreationContext context, ISubDependencyResolver parentResolver,
                            ComponentModel model, DependencyModel dependency)
    {
        return dependency.DependencyKey.ToLowerInvariant().Equals("serviceid") &&
               dependency.TargetType == typeof(string);

    }
    public object Resolve(CreationContext context, ISubDependencyResolver parentResolver,
                            ComponentModel model, DependencyModel dependency)
    {
        return model.Name;
    }
    #endregion
}

In CanResolve method, we tell the container that we are able to resolve a dependency only when it is service id, and in the Resolve method we return that dependency to be the service id.

There are still missing points in the code, we should also check if this parameter is defined somewhere in configuration. If that is the case, we shouldn’t resolve it on our own, but leave the container handles this.

Very easy isn’t it?

kick it on DotNetKicks.com

, , ,

Hello Blogosphere!

19. November 2008

Hello, my name is Tuna Toksoz, an undergraduate junior at Computer Engineering Department of Bogazici University. I am currently helping as a committer to the development of some well-known opensource projects such as NHibernate and Castle. I would like to share my findings and the solutions I come up with for the problems I faced.

I’d like to thank Mehmet Turac for encouraging and his passion (!) in providing me a reliable database!

PS: I also would like to Berker Peksag for reminding me to thank him!

Some tips on events

19. November 2008
public class PluginService:IPluginService
{
    public event EventHandler<EventArgs> PluginStarted;
    public event EventHandler<EventArgs> PluginStarting;
    public void StartPlugin(int id)
    {
        PluginStarting(this, EventArgs.Empty);
        //Do some work
        PluginStarted(this, EventArgs.Empty);
    }
}

There is something obviously wrong with this code.

First of all, it is not doing the null check on the event. One should not assume that event will always have handlers.

There are 2 solutions to that issue:

  1. Dummy operation  
    public class PluginService:IPluginService
    {
        public event EventHandler<EventArgs> PluginStarted = delegate { };
        public event EventHandler<EventArgs> PluginStarting = delegate { };
        public void StartPlugin(int id)
        {
            PluginStarting(this, EventArgs.Empty);
            //Do some work
            PluginStarted(this, EventArgs.Empty);
        }
    }


    or some people prefer null object pattern but it is restricted to some specific delegate type.

    public class PluginService:IPluginService
    {
        public event EventHandler<EventArgs> PluginStarted = NullSubscriber.For<EventArgs>();
        public event EventHandler<EventArgs> PluginStarting = NullSubscriber.For<EventArgs>();
        public void StartPlugin(int id)
        {
            PluginStarting(this, EventArgs.Empty);
            //Do some work
            PluginStarted(this, EventArgs.Empty);
        }
    }

     

  2. Null Check
    First try would be to do the null check with a simple if:
    public class PluginService:IPluginService
    {
        public event EventHandler<EventArgs> PluginStarted;
        public event EventHandler<EventArgs> PluginStarting;
        public void StartPlugin(int id)
        {
            if (PluginStarting != null)
                PluginStarting(this, EventArgs.Empty);
            //Do some work
            if (PluginStarted!=null)
                PluginStarted(this, EventArgs.Empty);
        }
    }



    This wouldn’t work, since during the execution after the if is evaluated, the event handler may unsubscribe from the event, which will result in a null reference exception in the runtime(which is hard to catch in development)

    Another and the correct one try is:

    public class PluginService:IPluginService
    {
        public event EventHandler<EventArgs> PluginStarted;
        public event EventHandler<EventArgs> PluginStarting;
        public void StartPlugin(int id)
        {
            var handler = PluginStarting;
            if (handler != null)
                handler(this, EventArgs.Empty);
            //Do some work
            handler = PluginStarted;
            if (handler != null)
                handler(this, EventArgs.Empty);
        }
    }


    The key point here is not the null check, but how we do the null check. Since the events are immutable, we are now free to assign it. It won’t cause an issue when one of the subscribers unsubscribe.
    (thanks to Ayende for reminding us the Race condition)

    I think this is enough for the first post

    kick it on DotNetKicks.com

, ,