1 /*
2 * Copyright 2012 The Netty Project
3 *
4 * The Netty Project licenses this file to you under the Apache License,
5 * version 2.0 (the "License"); you may not use this file except in compliance
6 * with the License. You may obtain a copy of the License at:
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations
14 * under the License.
15 */
16 package io.netty.util;
17
18 import io.netty.util.internal.PlatformDependent;
19
20 import java.util.concurrent.ConcurrentMap;
21
22 import static io.netty.util.internal.ObjectUtil.checkNotNull;
23
24 /**
25 * Key which can be used to access {@link Attribute} out of the {@link AttributeMap}. Be aware that it is not be
26 * possible to have multiple keys with the same name.
27 *
28 *
29 * @param <T> the type of the {@link Attribute} which can be accessed via this {@link AttributeKey}.
30 */
31 @SuppressWarnings({ "UnusedDeclaration", "deprecation" }) // 'T' is used only at compile time
32 public final class AttributeKey<T> extends UniqueName {
33
34 @SuppressWarnings("rawtypes")
35 private static final ConcurrentMap<String, AttributeKey> names = PlatformDependent.newConcurrentHashMap();
36
37 /**
38 * Creates a new {@link AttributeKey} with the specified {@param name} or return the already existing
39 * {@link AttributeKey} for the given name.
40 */
41 @SuppressWarnings("unchecked")
42 public static <T> AttributeKey<T> valueOf(String name) {
43 checkNotNull(name, "name");
44 AttributeKey<T> option = names.get(name);
45 if (option == null) {
46 option = new AttributeKey<T>(name);
47 AttributeKey<T> old = names.putIfAbsent(name, option);
48 if (old != null) {
49 option = old;
50 }
51 }
52 return option;
53 }
54
55 /**
56 * Returns {@code true} if a {@link AttributeKey} exists for the given {@code name}.
57 */
58 public static boolean exists(String name) {
59 checkNotNull(name, "name");
60 return names.containsKey(name);
61 }
62
63 /**
64 * Creates a new {@link AttributeKey} for the given {@param name} or fail with an
65 * {@link IllegalArgumentException} if a {@link AttributeKey} for the given {@param name} exists.
66 */
67 @SuppressWarnings("unchecked")
68 public static <T> AttributeKey<T> newInstance(String name) {
69 checkNotNull(name, "name");
70 AttributeKey<T> option = new AttributeKey<T>(name);
71 AttributeKey<T> old = names.putIfAbsent(name, option);
72 if (old != null) {
73 throw new IllegalArgumentException(String.format("'%s' is already in use", name));
74 }
75 return option;
76 }
77
78 /**
79 * @deprecated Use {@link #valueOf(String)} instead.
80 */
81 @Deprecated
82 public AttributeKey(String name) {
83 super(name);
84 }
85 }