| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using System.Threading; |
| | | 3 | | |
| | | 4 | | namespace Itinero.Routing.Flavours.Dijkstra; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Reuses search instances so their trees, heaps and visited sets are not rebuilt |
| | | 8 | | /// per route. Rented per call and returned in a finally, not [ThreadStatic] — async |
| | | 9 | | /// continuations can resume on a thread already running another search. |
| | | 10 | | /// </summary> |
| | | 11 | | internal static class SearchPool<T> where T : class, new() |
| | | 12 | | { |
| | | 13 | | /// Bounds retention: each instance holds buffers sized for its largest search. |
| | | 14 | | private const int MaxRetained = 64; |
| | | 15 | | |
| | 2 | 16 | | private static readonly ConcurrentBag<T> Pool = new(); |
| | | 17 | | private static int _retained; |
| | | 18 | | |
| | | 19 | | public static T Rent() |
| | 11668 | 20 | | { |
| | 11671 | 21 | | if (!Pool.TryTake(out var item)) return new T(); |
| | | 22 | | |
| | 11665 | 23 | | Interlocked.Decrement(ref _retained); |
| | 11665 | 24 | | return item; |
| | 11668 | 25 | | } |
| | | 26 | | |
| | | 27 | | public static void Return(T item) |
| | 11668 | 28 | | { |
| | 11668 | 29 | | if (Interlocked.Increment(ref _retained) > MaxRetained) |
| | 0 | 30 | | { |
| | 0 | 31 | | Interlocked.Decrement(ref _retained); |
| | 0 | 32 | | return; |
| | | 33 | | } |
| | | 34 | | |
| | 11668 | 35 | | Pool.Add(item); |
| | 11668 | 36 | | } |
| | | 37 | | } |