Files
OpenRA/OpenRA.Mods.Common/Pathfinder/CellInfoLayerPool.cs
RoosterDragon 519be4374c Fixed pooling of layers used for pathfinding.
The previous implementation:
- Was failing to dispose of pooled layers.
- Was using a finalizer to allow undisposed layers to be reused.

This means all pooled layers are kept alive indefinitely until the map changes. If the finalizer is slow for any reason then the pathfiinder will allocate new layers when the pool runs out. Since these new layers are eventually stuffed back into the pool when the finalizer does run, this can theoretically leak unbounded memory until the pool goes out of scope. In practice it would leak tens of megabytes.

The new implementation ensures layers are disposed and pooled correctly to allow proper memory reuse. It also introduces some safeguards against memory leaks:
- A cap is set on the number of pooled layers. If more concurrent layers are needed than this, then the excess layers will not be pooled but instead be allowed to be garbage collected.
- No finalizer. An implementation that fails to call dispose simply allows the layer to be garbage collected instead.
2015-09-16 21:25:46 +01:00

78 lines
1.8 KiB
C#

#region Copyright & License Information
/*
* Copyright 2007-2015 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Drawing;
namespace OpenRA.Mods.Common.Pathfinder
{
sealed class CellInfoLayerPool
{
const int MaxPoolSize = 4;
readonly Stack<CellLayer<CellInfo>> pool = new Stack<CellLayer<CellInfo>>(MaxPoolSize);
readonly CellLayer<CellInfo> defaultLayer;
public CellInfoLayerPool(Map map)
{
defaultLayer =
CellLayer<CellInfo>.CreateInstance(
mpos => new CellInfo(int.MaxValue, int.MaxValue, mpos.ToCPos(map), CellStatus.Unvisited),
new Size(map.MapSize.X, map.MapSize.Y),
map.TileShape);
}
public PooledCellInfoLayer Get()
{
return new PooledCellInfoLayer(this);
}
CellLayer<CellInfo> GetLayer()
{
CellLayer<CellInfo> layer = null;
lock (pool)
if (pool.Count > 0)
layer = pool.Pop();
if (layer == null)
layer = new CellLayer<CellInfo>(defaultLayer.Shape, defaultLayer.Size);
layer.CopyValuesFrom(defaultLayer);
return layer;
}
void ReturnLayer(CellLayer<CellInfo> layer)
{
lock (pool)
if (pool.Count < MaxPoolSize)
pool.Push(layer);
}
public class PooledCellInfoLayer : IDisposable
{
public CellLayer<CellInfo> Layer { get; private set; }
CellInfoLayerPool layerPool;
public PooledCellInfoLayer(CellInfoLayerPool layerPool)
{
this.layerPool = layerPool;
Layer = layerPool.GetLayer();
}
public void Dispose()
{
if (Layer == null)
return;
layerPool.ReturnLayer(Layer);
Layer = null;
layerPool = null;
}
}
}
}