diff --git a/common/src/main/java/io/netty/util/ConstantPool.java b/common/src/main/java/io/netty/util/ConstantPool.java index b6ff0dd682..fb6a8d2376 100644 --- a/common/src/main/java/io/netty/util/ConstantPool.java +++ b/common/src/main/java/io/netty/util/ConstantPool.java @@ -55,31 +55,24 @@ public abstract class ConstantPool> { * @param name the name of the {@link Constant} */ public T valueOf(String name) { - if (name == null) { - throw new NullPointerException("name"); - } - - if (name.isEmpty()) { - throw new IllegalArgumentException("empty name"); - } + T c; synchronized (constants) { - T c = constants.get(name); - if (c == null) { - c = newConstant(nextId, name); - constants.put(name, c); - nextId ++; + if (exists(name)) { + c = constants.get(name); + } else { + c = newInstance0(name); } - - return c; } + + return c; } /** * Returns {@code true} if a {@link AttributeKey} exists for the given {@code name}. */ public boolean exists(String name) { - ObjectUtil.checkNotNull(name, "name"); + checkNotNullAndNotEmpty(name); synchronized (constants) { return constants.containsKey(name); } @@ -91,25 +84,33 @@ public abstract class ConstantPool> { */ @SuppressWarnings("unchecked") public T newInstance(String name) { - if (name == null) { - throw new NullPointerException("name"); + if (exists(name)) { + throw new IllegalArgumentException(String.format("'%s' is already in use", name)); } + T c = newInstance0(name); + + return c; + } + + // Be careful that this dose not check whether the argument is null or empty. + private T newInstance0(String name) { + synchronized (constants) { + T c = newConstant(nextId, name); + constants.put(name, c); + nextId++; + return c; + } + } + + private String checkNotNullAndNotEmpty(String name) { + ObjectUtil.checkNotNull(name, "name"); + if (name.isEmpty()) { throw new IllegalArgumentException("empty name"); } - synchronized (constants) { - T c = constants.get(name); - if (c == null) { - c = newConstant(nextId, name); - constants.put(name, c); - nextId ++; - } else { - throw new IllegalArgumentException(String.format("'%s' is already in use", name)); - } - return c; - } + return name; } protected abstract T newConstant(int id, String name);