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 d60c6e76e7..1baeecbf7c 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 final class PlatformDependent { 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 + ')'); } } }