Uploaded image for project: 'Lucene.Net'
  1. Lucene.Net
  2. LUCENENET-358

CloseableThreadLocal memory leak in LocalDataStoreSlot (with workaround)

    XMLWordPrintableJSON

Details

    Description

      Recently we have been suffering from a severe memory leak when executing intense open/close operations on IndexSearcher and IndexModifier.
      Memory profiling showed that memory is being held by LocalDataStore[] objects.

      After some digging, the root of the problem has been found in CloseableThreadLocal class:

      private System.LocalDataStoreSlot t = System.Threading.Thread.AllocateDataSlot();

      What we see is that every instantiated object of CloseableThreadLocal causes new data slot allocation performed for every thread.
      Thread.AllocateDataSlot() does not simply allocate a new slot, replacing an old one, but enlarging an existing buffer in-thread, appending data to the end of internal LocalDataStore[] collection, which causes a severe memory leak .

      As long as "t" variable is instantiated on every object creation, and (in current class implementation) every object is used by a single thread, replacing "private System.LocalDataStoreSlot t = System.Threading.Thread.AllocateDataSlot();" with simple "private object dataSlot;" and removing "hardRefs" Dictionary solves the problem and prevents memory leak.

      We have tried to implement the expected behavior by using [ThreadStatic] attribute instead of LocalDataStoreSlot, but the attempt failed because of unexpected exceptions being thrown.

      Patch can be found at Lucene.Net repository under

      Attachments

        1. TestMemLeakage.zip
          5 kB
          Digy
        2. CloseableThreadLocal MemoryLeak.patch
          3 kB
          Rezgar Cadro
        3. CloseableThreadLocal.patch
          3 kB
          Digy
        4. CloseableThreadLocal.diff
          3 kB
          Robert Jordan
        5. CloseableThreadLocal.diff
          1 kB
          Robert Jordan

        Activity

          People

            digydigy Digy
            rezgar Rezgar Cadro
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: