# Friday, September 03, 2004
« Geekman | Main | Data Centre Security »

One of the nice things about System.String is that two variables having the same contents will point to the same object once they have been interned. So you have the following:

string s1 = "abcdef";
string s2 = "abcdef";

object o1 = string.Intern(s1);
object o2 = string.Intern(s2);

Debug.Assert(o1 == o2);

This can be put to good use when you want to use caching... If the non-cache lookup is expensive, say a database call, you want to ensure that the lookup operation will only happen once in the presence of multiple threads. The lock(cache) keyword is ideal but not very granular. An alternative is the lock the cache key:

public string GetFromCacheOrLookup(string key)
{
    lock (string.Intern(key))
    {
        string result = (string)cache[key];

        if (result == null)
        {
            result = LookupFromDatabase(key);
            cache[key] = result;
        }

        return result;
    }
}

This method allows multiple threads to perform the expensive lookup as long as the key is different; if not then they wait for the initial lookup to complete before continuing.

by This posting is provided "AS IS" with no warranties, and confers no rights.
posted on Friday, September 03, 2004 1:07:43 PM (GMT Daylight Time, UTC+01:00)  #    Comments [3] Trackback
Related posts:
Testing Windows Forms Applications
Messing around with the Insert Code plug-in
Link Dump
Debugging FullTrust VSTO InfoPath Forms
Which version of the .NET Framework does Excel load?
Missing content from XmlSerializer output
Tuesday, March 08, 2005 3:34:52 PM (GMT Standard Time, UTC+00:00)
That is a nice trick. I'm looking for something similar in Java. Do you have any pointers?
Tuesday, March 08, 2005 3:37:36 PM (GMT Standard Time, UTC+00:00)
Sorry Stephen, I don't know Java at all... It's on my todo list but I think there will always be more fun things to learn.

James.
Friday, May 20, 2005 2:58:13 PM (GMT Daylight Time, UTC+01:00)
Thanks for the trick.
I have thinked out the same solution in Java and just
search the Net to see whether the someone already found it --
and found your article :)

In Java code will look like:

public String getFromCacheOrLookup(String key)
{
synchronized (key.intern())
...
}

Regards.
Eugene Voytitsky
Comments are closed.