Lock-Free Service Locator
Posted by reshefm in Service locator, multithreading on June 18th, 2008
Usually, when developing small application there is no real justification for using a full-fledged IoC container for managing services.
However, cross-cutting , single instance services are something common that still has to managed. This leaves us with the following options for accessing services:
- Implement the service as singleton.
- Move the service reference between objects.
- Use a service locator.
I don’t like the first option as it introduces global variables to the application and the second option is tedious very hard to manage.
This leaves us with the service locator which in general should be the only singleton(static) in the application and provide access to the services according to their interface.
The service locator usually looks like that:
public static class ServiceLocator{ private static readonly IDictionary<Type, object> services = new Dictionary<Type, object>(); private static readonly object locker = new object(); public static void SetService<T>(T instance) where T : class { if (instance == null) throw new ArgumentNullException("instance"); lock (locker) { services.Add(typeof(T), instance); } } public static T GetService<T>() where T : class { object service; lock (locker) { services. TryGetValue(typeof(T), out service); } return service as T; }}
It hold a dictionary of services. The key is the type and the value is the instance. It is quite simple, however I do not like the fact that it has to lock the services dictionary on each access.
When trying to eliminate the need for locking, I remembered this post by Arnon and it inspired my to try this approach:
public static class ServiceLocator{ private class Resolver<T> where T:class { private static T theInstance; public static void Create(T instance) { if (instance == null) throw new ArgumentNullException("instance"); Interlocked. Exchange(ref theInstance, instance); } public static T Instance { get { return theInstance; } } } public static void SetService<T>(T instance) where T:class { Resolver<T>.Create(instance); } public static T GetService<T>() where T:class { return Resolver<T>.Instance; }}
Pay attention to the Resolver private class. For every type T that is specified as a generic parameter, a new type, Resolver<SomeType> will be created and the static field, theInstance, will be set to the service instance.
What did we achieve here?
In the previous implementation we had to lock the dictionary on every read or write. In the new implementation there is no need to lock for read and the lock for writing was changed to Interlocked which has better performance so we have better concurrency.
No dictionary. Although it is negligible there is no need to search a dictionary. Besides, I always felt that something like service resolution should be something which is related to the infrastructure and should not be managed by a dictionary and I think this implementation better achieves it.
Code semantics
Posted by reshefm in Uncategorized on March 23rd, 2008
As I started a new job I was introduced to a new codebase. This happens to any developer who is starting a new job or a new role.
Since people are different, their approaches towards code is different as well, and were one developer gives his data-access interfaces and objects the suffix ‘DAO’, another developer will suffix it with ‘Repository’, hence, we might get ‘ICoustomerDAO’ or ‘ICustomerRepository’.
The meaning is the same - a service that is charge of storing and retrieving information about a customer.
As I mentioned at the beginning, I was recently introduced to a new codebase that has its own semantics. Some of these semantics were trivial like using the convention of ‘Sink’. I immediately understood that a sink is a recipient of data and it is the end of the road for this data. Examples are ConsoleSink which writes to the console and DBSink which writes to the database.
This however, is a simple example as a system is more complex than that. There are other "hidden" semantics that are just the result of differences between people and the way they things.
The example I used with the DAO/Repository in taken from the semantics of Domain-Driven Development (DDD) which gives very high importance to the way things are expressed. The base for DDD is first of all defining an ubiquitous language that is used to define the entities in the system and the relations between them.
I believe that if a software project will have a defined semantics, the amount of the mess that is usually a part of a codebase will dramatically be reduced, it will be easier to get familiar with the code and maintenance will be easier.
Dynamic proxies
Posted by reshefm in dynamic proxy, reflection on November 22nd, 2007
A dynamic proxy is an approach that is not fully natively supported in .net but natively exists in java.
What a proxy means, is to wrap an object with with wrapper that intercepts call to that object and does something in addition.
What is it good for? A naive example is to add a proxy that log calls to methods of an object.
A more real world example is to use proxy in an O/R mapper. The mapper can create proxies on top of the domain object and intercept calls to properties in order to fetch data from the db and track changes to the data that will later be persisted (NHibernate works this way).
The idea of dynamic proxy is to provide an implementation of an interceptor and attach it to the proxy. From now on, all calls to methods will pay through the interceptor which, for the logging example, logs every call to the method. Concrete examples can be found in the link at the bottom of this post.
The .net native implementation for dynamic proxies is by using ContextBoundObject or MarsalByRefObject. This approach is limited since you have to inherit from one of these classes which is not clean.
There are several implementations of dynamic proxies that do not interfere with inheritance hierarchy of your code.
Here are some examples:
3) LinFu
Mutual exclusion when Remoting
Posted by reshefm in multithreading, remoting on November 22nd, 2007
Another tip from Gal:“
Just a small tip that might have saved me a few good hours:
A Mutex can be released only by the thread that originally locked it.
A semaphore can be released by any thread.
I used a mutex at the beginning, while locking and releasing on different threads, and at the threadpool desire, got (”sometimes” is the WORST one) an
ApplicationException - Object synchronization method was called from an unsynchronized block of code.
Usually this means that the mutex is not locked but still tries to be released – check this out.
But in my case (first remoting call locks an object and the second releases), it was just that a mutex was the wrong sync method, and a semaphore quickly solved the problem.
As mentioned in the link, the error message need some work.“
ref/out key words for reference types
Posted by reshefm in Uncategorized on November 15th, 2007
This tip is the courtesy of Gal.
It surprised and embarrassed me to realize that I didn’t know it.
When a reference type is passed to a method without using the ref or out keywords, a new reference is created inside the method and it points to the same location in the memory as the reference that was passed so we have two “pointers” to the same location in memory.
In case the the reference inside the method is set to a different location, the reference that was passed does not change.
When the ref/out keywords are used, we have only one reference inside and outside the method so if the reference is changed to point to another location and it happens inside the method, the outer reference is changed too.
Basic stuff…
ThreadStatic attribute
Posted by reshefm in Uncategorized on November 15th, 2007
According to the msdn documentation, the ThreadStatic attribute “Indicates that the value of a static field is unique for each thread.”
A practical use for it can be a registrar implementation. A registrar can be used as a static entry point to store context data for say, a request that is being processed by several classes that need to share data.
Implementation example:
public static class Registrar{ [ThreadStatic] private static Dictionary<string, object> m_registrar = null; private static Dictionary<string, object> LocalDictionary { get { if (m_registrar == null) { m_registrar = new Dictionary<string, object>(); } return m_registrar; } } public static object Get(string key) { return LocalDictionary[key]; } public static void Set(string key, object value) { LocalDictionary[key] = value; }}
Now since the m_registrar is marked with ThreadStatic attribute, is static per thread, which means that no locking is required and no data corruption can occur.
A real world example for using such strategy is HttpContext.Items
Gilad pointed out two important points:
- ASP.NET is changing threads under the hood so don’t use it there since u will most probably get your data corrupted. The HttpContext knows how to handle that so use it.
- When using a thread pool, the threads are not killed and so when a thread completes execution and returned to the pool, the static data is still kept. In this case u should use an execution wrapper than clears the per thread static data after the thread complete execution.
Data Type aliasing
Posted by reshefm in Uncategorized on November 14th, 2007
There is a feature in .net that is not commonly remembered and it is Data Type aliasing.
What it means is that u give a data type a different name.
I can see two uses for it:
1) Enhance code readability:
Instead of having very long type declarations such as when using generic types inside generic types, u can assign an alias to that declaration. Here is an example:
// Aliasing using HashOfHashes = Dictionary<string, Dictionary<string, List<string>>>;
public class AliasExample { HashOfHashes m_hash;
public AliasExample() { m_hash = new HashOfHashes(); }
public HashOfHashes MyHash { get { return m_hash; } } }
2) Alias data types that are prone to change:
An example is an identifier property of class. It can save a lot find&replace when changing code like changing the identifier of a member from int to Guid and it better shows intent. For example:
// Aliasing using MemberIdentidfier = Guid;
public class MemberWithAlias { private MemberIdentidfier m_id; private string m_name;
public MemberWithAlias (MemberIdentidfier id) { m_id = id; }
public MemberIdentidfier Id { get { return m_id; } }
public string Name { get { return m_name; } set { m_name = value; } } }
Primitive but efficient way for profiling (on development machine)
Posted by reshefm in Uncategorized on November 14th, 2007
Small thing I read about. It is so simple and obvious but I never thought about it…
In the lack of a decent profiler,
if u observe that a certain process takes a large amount of time (such as system startup),
start the debugger and while the time consuming task is running, click the pause button in VS.
Now take a look at the call stack to see which method take the time to execute.
