001/*
002 *  Licensed to the Apache Software Foundation (ASF) under one
003 *  or more contributor license agreements.  See the NOTICE file
004 *  distributed with this work for additional information
005 *  regarding copyright ownership.  The ASF licenses this file
006 *  to you under the Apache License, Version 2.0 (the
007 *  "License"); you may not use this file except in compliance
008 *  with the License.  You may obtain a copy of the License at
009 *
010 *    http://www.apache.org/licenses/LICENSE-2.0
011 *
012 *  Unless required by applicable law or agreed to in writing,
013 *  software distributed under the License is distributed on an
014 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 *  KIND, either express or implied.  See the License for the
016 *  specific language governing permissions and limitations
017 *  under the License.
018 *
019 */
020package org.apache.mina.filter.codec;
021
022import org.apache.mina.core.buffer.IoBuffer;
023import org.apache.mina.core.session.IoSession;
024
025/**
026 * A {@link ProtocolDecoder} implementation which decorates an existing decoder
027 * to be thread-safe.  Please be careful if you're going to use this decorator
028 * because it can be a root of performance degradation in a multi-thread
029 * environment.  Also, by default, appropriate synchronization is done
030 * on a per-session basis by {@link ProtocolCodecFilter}.  Please use this
031 * decorator only when you need to synchronize on a per-decoder basis, which
032 * is not common.
033 *
034 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
035 */
036public class SynchronizedProtocolDecoder implements ProtocolDecoder {
037    private final ProtocolDecoder decoder;
038
039    /**
040     * Creates a new instance which decorates the specified <tt>decoder</tt>.
041     * 
042     * @param decoder The decorated decoder
043     */
044    public SynchronizedProtocolDecoder(ProtocolDecoder decoder) {
045        if (decoder == null) {
046            throw new IllegalArgumentException("decoder");
047        }
048        
049        this.decoder = decoder;
050    }
051
052    /**
053     * @return the decoder this decoder is decorating.
054     */
055    public ProtocolDecoder getDecoder() {
056        return decoder;
057    }
058
059    public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
060        synchronized (decoder) {
061            decoder.decode(session, in, out);
062        }
063    }
064
065    /**
066     * {@inheritDoc}
067     */
068    public void finishDecode(IoSession session, ProtocolDecoderOutput out) throws Exception {
069        synchronized (decoder) {
070            decoder.finishDecode(session, out);
071        }
072    }
073
074    /**
075     * {@inheritDoc}
076     */
077    public void dispose(IoSession session) throws Exception {
078        synchronized (decoder) {
079            decoder.dispose(session);
080        }
081    }
082}