diff --git a/common/src/main/java/io/netty/util/internal/PlatformDependent.java b/common/src/main/java/io/netty/util/internal/PlatformDependent.java index d60c6e76e701..1baeecbf7c90 100644 --- a/common/src/main/java/io/netty/util/internal/PlatformDependent.java +++ b/common/src/main/java/io/netty/util/internal/PlatformDependent.java @@ -649,16 +649,12 @@ public static void freeDirectNoCleaner(ByteBuffer buffer) { private static void incrementMemoryCounter(int capacity) { if (DIRECT_MEMORY_COUNTER != null) { - for (;;) { - long usedMemory = DIRECT_MEMORY_COUNTER.get(); - long newUsedMemory = usedMemory + capacity; - if (newUsedMemory > DIRECT_MEMORY_LIMIT) { - throw new OutOfDirectMemoryError("failed to allocate " + capacity - + " byte(s) of direct memory (used: " + usedMemory + ", max: " + DIRECT_MEMORY_LIMIT + ')'); - } - if (DIRECT_MEMORY_COUNTER.compareAndSet(usedMemory, newUsedMemory)) { - break; - } + long newUsedMemory = DIRECT_MEMORY_COUNTER.addAndGet(capacity); + if (newUsedMemory > DIRECT_MEMORY_LIMIT) { + DIRECT_MEMORY_COUNTER.addAndGet(-capacity); + throw new OutOfDirectMemoryError("failed to allocate " + capacity + + " byte(s) of direct memory (used: " + (newUsedMemory - capacity) + + ", max: " + DIRECT_MEMORY_LIMIT + ')'); } } }