ChallengeYour own ThreadLocal

time to read 4 min | 767 words

I found a bug in Lucene.NET that resulted in a memory leak in RavenDB. Take a look here (I have simplified the code to some extent, but the same spirit remains):

public class CloseableThreadLocal
{
    [ThreadStatic] private static Dictionary<object, object> slots;

    public static Dictionary<object, object> Slots
    {
        get { return slots ?? (slots = new Dictionary<object, object>()); }
    }

    public /*protected internal*/ virtual Object InitialValue()
    {
        return null;
    }

    public virtual Object Get()
    {
        object val;

        if (Slots.TryGetValue(this, out val))
        {
            return val;
        }
        val = InitialValue();
        Set(val);
        return val;
    }

    public virtual void Set(object val)
    {
        Slots[this] = val;
    }

    public virtual void Close()
    {
        if (slots != null)// intentionally using the field here, to avoid creating the instance
            slots.Remove(this);
    }
}

As you can imagine, this is a fairly elegant way of doing this (please note, .NET 4.0 have the ThreadLocal class, which I strongly recommend using). But it has one very serious flaw. It you don’t close the instance, you are going to leak some memory. As you can imagine, that is a pretty bad thing to do.

In general, I consider such designs as pretty bad bugs when writing managed code. We have the GC for a reason, and writing code that forces the user to manually manage memory is BAD for you. Here is an example showing the problem:

class Program
{
    static void Main(string[] args)
    {
        UseThreadLocal();
        GC.Collect(2);
GC.WaitForPendingFinalizers();
Console.WriteLine(CloseableThreadLocal.slots.Count); } private static void UseThreadLocal() { var tl = new CloseableThreadLocal(); tl.Set("hello there"); Console.WriteLine(tl.Get()); } }

This will show that after the UseThreadLocal() run and we force full collection, the value is still there.

Without using the builtin ThreadLocal, can you figure out a way to solve this?

Points goes to whoever does this with the minimum amount of changes to the code.

More posts in "Challenge" series:

  1. (31 Jan 2018) Find the bug in the fix–answer
  2. (30 Jan 2018) Find the bug in the fix
  3. (19 Jan 2017) What does this code do?
  4. (26 Jul 2016) The race condition in the TCP stack, answer
  5. (25 Jul 2016) The race condition in the TCP stack
  6. (28 Apr 2015) What is the meaning of this change?
  7. (26 Sep 2013) Spot the bug
  8. (27 May 2013) The problem of locking down tasks…
  9. (17 Oct 2011) Minimum number of round trips
  10. (23 Aug 2011) Recent Comments with Future Posts
  11. (02 Aug 2011) Modifying execution approaches
  12. (29 Apr 2011) Stop the leaks
  13. (23 Dec 2010) This code should never hit production
  14. (17 Dec 2010) Your own ThreadLocal
  15. (03 Dec 2010) Querying relative information with RavenDB
  16. (29 Jun 2010) Find the bug
  17. (23 Jun 2010) Dynamically dynamic
  18. (28 Apr 2010) What killed the application?
  19. (19 Mar 2010) What does this code do?
  20. (04 Mar 2010) Robust enumeration over external code
  21. (16 Feb 2010) Premature optimization, and all of that…
  22. (12 Feb 2010) Efficient querying
  23. (10 Feb 2010) Find the resource leak
  24. (21 Oct 2009) Can you spot the bug?
  25. (18 Oct 2009) Why is this wrong?
  26. (17 Oct 2009) Write the check in comment
  27. (15 Sep 2009) NH Prof Exporting Reports
  28. (02 Sep 2009) The lazy loaded inheritance many to one association OR/M conundrum
  29. (01 Sep 2009) Why isn’t select broken?
  30. (06 Aug 2009) Find the bug fixes
  31. (26 May 2009) Find the bug
  32. (14 May 2009) multi threaded test failure
  33. (11 May 2009) The regex that doesn’t match
  34. (24 Mar 2009) probability based selection
  35. (13 Mar 2009) C# Rewriting
  36. (18 Feb 2009) write a self extracting program
  37. (04 Sep 2008) Don't stop with the first DSL abstraction
  38. (02 Aug 2008) What is the problem?
  39. (28 Jul 2008) What does this code do?
  40. (26 Jul 2008) Find the bug fix
  41. (05 Jul 2008) Find the deadlock
  42. (03 Jul 2008) Find the bug
  43. (02 Jul 2008) What is wrong with this code
  44. (05 Jun 2008) why did the tests fail?
  45. (27 May 2008) Striving for better syntax
  46. (13 Apr 2008) calling generics without the generic type
  47. (12 Apr 2008) The directory tree
  48. (24 Mar 2008) Find the version
  49. (21 Jan 2008) Strongly typing weakly typed code
  50. (28 Jun 2007) Windsor Null Object Dependency Facility