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.session.IoSession;
023
024/**
025 * A {@link ProtocolEncoder} implementation which decorates an existing encoder
026 * to be thread-safe.  Please be careful if you're going to use this decorator
027 * because it can be a root of performance degradation in a multi-thread
028 * environment.  Please use this decorator only when you need to synchronize
029 * on a per-encoder basis instead of on a per-session basis, which is not
030 * common.
031 *
032 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
033 */
034public class SynchronizedProtocolEncoder implements ProtocolEncoder {
035    private final ProtocolEncoder encoder;
036
037    /**
038     * Creates a new instance which decorates the specified <tt>encoder</tt>.
039     * @param encoder The decorated encoder
040     */
041    public SynchronizedProtocolEncoder(ProtocolEncoder encoder) {
042        if (encoder == null) {
043            throw new IllegalArgumentException("encoder");
044        }
045        this.encoder = encoder;
046    }
047
048    /**
049     * @return the encoder this encoder is decorating.
050     */
051    public ProtocolEncoder getEncoder() {
052        return encoder;
053    }
054
055    /**
056     * {@inheritDoc}
057     */
058    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
059        synchronized (encoder) {
060            encoder.encode(session, message, out);
061        }
062    }
063
064    /**
065     * {@inheritDoc}
066     */
067    public void dispose(IoSession session) throws Exception {
068        synchronized (encoder) {
069            encoder.dispose(session);
070        }
071    }
072}