1 /*
2 * Copyright 2013 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
17 package io.netty.channel;
18
19 import io.netty.util.internal.InternalThreadLocalMap;
20
21 import java.util.Map;
22
23 /**
24 * Skelton implementation of a [email protected] ChannelHandler}.
25 */
26 public abstract class ChannelHandlerAdapter implements ChannelHandler {
27
28 // Not using volatile because it's used only for a sanity check.
29 boolean added;
30
31 /**
32 * Return [email protected] true} if the implementation is [email protected] Sharable} and so can be added
33 * to different [email protected] ChannelPipeline}s.
34 */
35 public boolean isSharable() {
36 /**
37 * Cache the result of [email protected] Sharable} annotation detection to workaround a condition. We use a
38 * [email protected] ThreadLocal} and [email protected] WeakHashMap} to eliminate the volatile write/reads. Using different
39 * [email protected] WeakHashMap} instances per [email protected] Thread} is good enough for us and the number of
40 * [email protected] Thread}s are quite limited anyway.
41 *
42 * See <a href="https://github.com/netty/netty/issues/2289">#2289</a>.
43 */
44 Class<?> clazz = getClass();
45 Map<Class<?>, Boolean> cache = InternalThreadLocalMap.get().handlerSharableCache();
46 Boolean sharable = cache.get(clazz);
47 if (sharable == null) {
48 sharable = clazz.isAnnotationPresent(Sharable.class);
49 cache.put(clazz, sharable);
50 }
51 return sharable;
52 }
53
54 /**
55 * Do nothing by default, sub-classes may override this method.
56 */
57 @Override
58 public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
59 // NOOP
60 }
61
62 /**
63 * Do nothing by default, sub-classes may override this method.
64 */
65 @Override
66 public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
67 // NOOP
68 }
69
70 /**
71 * Calls [email protected] ChannelHandlerContext#fireExceptionCaught(Throwable)} to forward
72 * to the next [email protected] ChannelHandler} in the [email protected] ChannelPipeline}.
73 *
74 * Sub-classes may override this method to change behavior.
75 */
76 @Override
77 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
78 ctx.fireExceptionCaught(cause);
79 }
80 }