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 */ 040 public SynchronizedProtocolEncoder(ProtocolEncoder encoder) { 041 if (encoder == null) { 042 throw new IllegalArgumentException("encoder"); 043 } 044 this.encoder = encoder; 045 } 046 047 /** 048 * Returns the encoder this encoder is decorating. 049 */ 050 public ProtocolEncoder getEncoder() { 051 return encoder; 052 } 053 054 public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { 055 synchronized (encoder) { 056 encoder.encode(session, message, out); 057 } 058 } 059 060 public void dispose(IoSession session) throws Exception { 061 synchronized (encoder) { 062 encoder.dispose(session); 063 } 064 } 065}