Skip to content

Commit

Permalink
RavenDB-23705 - code reuse
Browse files Browse the repository at this point in the history
  • Loading branch information
grisha-kotler committed Feb 12, 2025
1 parent f338227 commit c7166b4
Showing 1 changed file with 8 additions and 27 deletions.
35 changes: 8 additions & 27 deletions src/Sparrow/Utils/NativeMemory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -112,21 +112,18 @@ public ThreadStats()
}
}

public static void Free(byte* ptr, long size, ThreadStats stats)
public static void Free(byte* ptr, long size)
{
Debug.Assert(ptr != null);

UpdateMemoryStatsForThread(stats, size);
Interlocked.Add(ref _totalAllocatedMemory, -size);

Marshal.FreeHGlobal((IntPtr)ptr);
}

public static void Free(byte* ptr, long size)
public static void Free(byte* ptr, long size, ThreadStats stats)
{
Debug.Assert(ptr != null);
Interlocked.Add(ref _totalAllocatedMemory, -size);
Marshal.FreeHGlobal((IntPtr)ptr);
Free(ptr, size);

UpdateMemoryStatsForThread(stats, size);
}

public static byte* AllocateMemory(long size)
Expand All @@ -153,25 +150,9 @@ public static void Free(byte* ptr, long size)
public static byte* AllocateMemory(long size, out ThreadStats thread)
{
thread = ThreadAllocations.Value;

// Allocating when there isn't enough commit charge available is dangerous, on Linux, the OOM
// will try to kill us. On Windows, we might get into memory allocation failures that are not
// fun, so let's try to avoid it explicitly.
// This is not expected to be called frequently, since we are caching the memory used here

LowMemoryNotification.AssertNotAboutToRunOutOfMemory();

try
{
var ptr = (byte*)Marshal.AllocHGlobal((IntPtr)size).ToPointer();
thread.Allocations += size;
Interlocked.Add(ref _totalAllocatedMemory, size);
return ptr;
}
catch (OutOfMemoryException e)
{
return ThrowFailedToAllocate(size, thread, e);
}
var ptr = AllocateMemory(size);
thread.Allocations += size;
return ptr;
}

public static void IncrementLuceneManagedAllocations(long size)
Expand Down

0 comments on commit c7166b4

Please sign in to comment.