View Javadoc

1   /*
2    *  Licensed to the Apache Software Foundation (ASF) under one
3    *  or more contributor license agreements.  See the NOTICE file
4    *  distributed with this work for additional information
5    *  regarding copyright ownership.  The ASF licenses this file
6    *  to you under the Apache License, Version 2.0 (the
7    *  "License"); you may not use this file except in compliance
8    *  with the License.  You may obtain a copy of the License at
9    *
10   *    http://www.apache.org/licenses/LICENSE-2.0
11   *
12   *  Unless required by applicable law or agreed to in writing,
13   *  software distributed under the License is distributed on an
14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *  KIND, either express or implied.  See the License for the
16   *  specific language governing permissions and limitations
17   *  under the License.
18   *
19   */
20  package org.apache.mina.filter.codec;
21  
22  import org.apache.mina.core.buffer.IoBuffer;
23  import org.apache.mina.core.session.IoSession;
24  
25  /**
26   * A {@link ProtocolDecoder} implementation which decorates an existing decoder
27   * to be thread-safe.  Please be careful if you're going to use this decorator
28   * because it can be a root of performance degradation in a multi-thread
29   * environment.  Also, by default, appropriate synchronization is done
30   * on a per-session basis by {@link ProtocolCodecFilter}.  Please use this
31   * decorator only when you need to synchronize on a per-decoder basis, which
32   * is not common.
33   *
34   * @author <a href="http://mina.apache.org">Apache MINA Project</a>
35   */
36  public class SynchronizedProtocolDecoder implements ProtocolDecoder {
37      private final ProtocolDecoder decoder;
38  
39      /**
40       * Creates a new instance which decorates the specified <tt>decoder</tt>.
41       */
42      public SynchronizedProtocolDecoder(ProtocolDecoder decoder) {
43          if (decoder == null) {
44              throw new IllegalArgumentException("decoder");
45          }
46          this.decoder = decoder;
47      }
48  
49      /**
50       * Returns the decoder this decoder is decorating.
51       */
52      public ProtocolDecoder getDecoder() {
53          return decoder;
54      }
55  
56      public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
57          synchronized (decoder) {
58              decoder.decode(session, in, out);
59          }
60      }
61  
62      public void finishDecode(IoSession session, ProtocolDecoderOutput out) throws Exception {
63          synchronized (decoder) {
64              decoder.finishDecode(session, out);
65          }
66      }
67  
68      public void dispose(IoSession session) throws Exception {
69          synchronized (decoder) {
70              decoder.dispose(session);
71          }
72      }
73  }