Challenge: Stop the leaks
Given the following API, can you think of a way that would prevent memory leaks?
public interface IBufferPool { byte[] TakeBuffer(int size); void ReturnBuffer(byte[] buffer); }
The problem with having something like this is that forgetting to return the buffer is going to cause a memory leak. Instead of having that I would like to have the application stop if a buffer is leaked. Leaked means that no one is referencing this buffer but it wasn’t returned to the pool.
What I would really like is that when running in debug mode, leaking a buffer would stop the entire application and tell me:
- That a buffer was leaked.
- What was the stack trace that allocated that buffer.
A solution will be posted tomorrow.
Comments
Inside your implementation, have a List <tuple<weakreference,>
That was a List<Tuple<WeakReference, StackTrace>> - you need a better blog engine :)
Standard IDisposable pattern (with finalizer hook) and some #IF DEBUG conditional blocks.
The only uncertainty would be relying upon a GC to occur in order for the finalizer to be run. But your tests can simulate that.
Forgot to say, the StackTrace can be captured in the constructor (wrapped in #IF DEBUG of course) and stored in a private field. Then when the finalizer is called, maybe use Environment.FailFast to print a nice message with that stack trace info.
Paul,
We are writing one right now.
Paul,
That makes it a pretty complex system, and you are doing a lot that you probably shouldn't.
There is also the issue of concurrent updates of timer & buffer takes/ returns.
Nathan,
Show me the code.
Paul if I remember correctly you'd still be tied to the GC.
According to the docs using a ConditionalWeakTable and maybe another list with the keys would be better.
Something like this is what I had in mind:
http://pastebin.com/ULNYap6u
Obviously you'd use using {} blocks, where appropriate, when dealing with the IBufferContext's.
This means that you now have to track IBufferContext, rather than just byte[]
There are better ways to do this.
In that case, I look forward to seeing the solution.
Maybe you could have a ConditionalWeakTable<byte[], T>, where T is a type that defines a finalizer and has a StackTrace. If you throw an exception on the finalizer thread, the process dies. When a buffer is returned to the pool, you remove it from the table.
Here's the code: https://gist.github.com/948237
Duarte,
Nice, and similar to how I decided to do this.
@Duarte
Could you please explain the solution. BufferPoolWithLeakDetection throws when system tries to garbage collect MemoryLeakException because buffer was already garbage collected. But if buffer was already garbage collected, where is the memory leak? No, it wasn't returned to the pool, but that's not what was asked.
Oh, sorry, didn't read carefully enough. That's exactly what was asked.