From 89da788fd23f3e745c799abb575a98696ebcdc2c Mon Sep 17 00:00:00 2001 From: Norman Maurer Date: Mon, 14 Mar 2016 09:09:24 +0100 Subject: [PATCH] Add proper synchronization when access metrics. Motivation: We also need to add synchronization when access fields to ensure we see the latest updates. Modifications: Add synchronization when read fields that are written concurrently. Result: Ensure correct visibility of updated. --- .../main/java/io/netty/buffer/PoolArena.java | 33 ++++++++++++++----- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/buffer/src/main/java/io/netty/buffer/PoolArena.java b/buffer/src/main/java/io/netty/buffer/PoolArena.java index d8a546319d..3ff5eb6787 100644 --- a/buffer/src/main/java/io/netty/buffer/PoolArena.java +++ b/buffer/src/main/java/io/netty/buffer/PoolArena.java @@ -444,7 +444,11 @@ abstract class PoolArena implements PoolArenaMetric { @Override public long numAllocations() { - return allocationsTiny.value() + allocationsSmall.value() + allocationsNormal + allocationsHuge.value(); + final long allocsNormal; + synchronized (this) { + allocsNormal = allocationsNormal; + } + return allocationsTiny.value() + allocationsSmall.value() + allocsNormal + allocationsHuge.value(); } @Override @@ -458,27 +462,31 @@ abstract class PoolArena implements PoolArenaMetric { } @Override - public long numNormalAllocations() { + public synchronized long numNormalAllocations() { return allocationsNormal; } @Override public long numDeallocations() { - return deallocationsTiny + deallocationsSmall + allocationsNormal + deallocationsHuge.value(); + final long deallocs; + synchronized (this) { + deallocs = deallocationsTiny + deallocationsSmall + allocationsNormal; + } + return deallocs + deallocationsHuge.value(); } @Override - public long numTinyDeallocations() { + public synchronized long numTinyDeallocations() { return deallocationsTiny; } @Override - public long numSmallDeallocations() { + public synchronized long numSmallDeallocations() { return deallocationsSmall; } @Override - public long numNormalDeallocations() { + public synchronized long numNormalDeallocations() { return deallocationsNormal; } @@ -493,8 +501,12 @@ abstract class PoolArena implements PoolArenaMetric { } @Override - public long numActiveAllocations() { - long val = numAllocations() - numDeallocations(); + public long numActiveAllocations() { + long val; + synchronized (this) { + val = allocationsNormal - deallocationsTiny - deallocationsSmall - allocationsNormal; + } + val -= deallocationsHuge.value(); return val >= 0 ? val : 0; } @@ -512,7 +524,10 @@ abstract class PoolArena implements PoolArenaMetric { @Override public long numActiveNormalAllocations() { - long val = numNormalAllocations() - numNormalDeallocations(); + final long val; + synchronized (this) { + val = allocationsNormal - deallocationsNormal; + } return val >= 0 ? val : 0; }