From 0f42719e9b05f2286964e1b5340fc2ac17c278dc Mon Sep 17 00:00:00 2001 From: Trustin Lee Date: Sun, 29 Apr 2012 23:08:59 +0900 Subject: [PATCH] Add DefaultAttributeMap --- .../io/netty/util/DefaultAttributeMap.java | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 common/src/main/java/io/netty/util/DefaultAttributeMap.java diff --git a/common/src/main/java/io/netty/util/DefaultAttributeMap.java b/common/src/main/java/io/netty/util/DefaultAttributeMap.java new file mode 100644 index 0000000000..37896fa8b9 --- /dev/null +++ b/common/src/main/java/io/netty/util/DefaultAttributeMap.java @@ -0,0 +1,46 @@ +package io.netty.util; + +import java.util.IdentityHashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + +public class DefaultAttributeMap implements AttributeMap { + + // Initialize lazily to reduce memory consumption. + private Map, Attribute> map; + + @Override + public synchronized Attribute attr(AttributeKey key) { + Map, Attribute> map = this.map; + if (map == null) { + // Not using ConcurrentHashMap due to high memory consumption. + map = this.map = new IdentityHashMap, Attribute>(2); + } + + Attribute attr = (Attribute) map.get(key); + if (attr == null) { + attr = new DefaultAttribute(); + map.put(key, attr); + } + return attr; + } + + private class DefaultAttribute extends AtomicReference implements Attribute { + + private static final long serialVersionUID = -2661411462200283011L; + + @Override + public T setIfAbsent(T value) { + if (compareAndSet(null, value)) { + return null; + } else { + return get(); + } + } + + @Override + public void remove() { + set(null); + } + } +}