Mina中关于多个同类型Filter(如ProtocolCodecFilter)实例共存问题的解决

1 篇文章 0 订阅

    最近在研读Mina框架的源码,刚好手头上有项目就直接用上了。直接进入正题……

    对Mina有点了解的人都知道,Mina中有一条FilterChain,我们可以向其中加入Filter实现链式处理。从源码看来,多数Filter(如ProtocolCodecFilter)在使用过程只允许有一个实例。若FilterChain中存在多个相同的实例,则有可能出现各种莫明其妙的问题,这些问题往往是超出你预料之外的,而且调试起来比较困难,除非你熟知Mina整个框架。究其原因,主要是在AttributeKey的问题,例:

public class ProtocolCodecFilter extends IoFilterAdapter {
    /** A logger for this class */
    private static final Logger LOGGER = LoggerFactory.getLogger(ProtocolCodecFilter.class);

    private static final Class<?>[] EMPTY_PARAMS = new Class[0];

    private static final IoBuffer EMPTY_BUFFER = IoBuffer.wrap(new byte[0]);

    private final AttributeKey ENCODER = new AttributeKey(ProtocolCodecFilter.class, "encoder");

    private final AttributeKey DECODER = new AttributeKey(ProtocolCodecFilter.class, "decoder");

    private final AttributeKey DECODER_OUT = new AttributeKey(ProtocolCodecFilter.class, "decoderOut");

    private final AttributeKey ENCODER_OUT = new AttributeKey(ProtocolCodecFilter.class, "encoderOut");
	
	...
	private ProtocolDecoderOutput getDecoderOut(IoSession session, NextFilter nextFilter) {
        ProtocolDecoderOutput out = (ProtocolDecoderOutput) session.getAttribute(DECODER_OUT);

        if (out == null) {
            // Create a new instance, and stores it into the session
            out = new ProtocolDecoderOutputImpl();
            session.setAttribute(DECODER_OUT, out);
        }

        return out;
    }
	...
}

    假设有两个ProtocolCodecFilter实例,那么同一时刻它们在各自的实例中AttributeKey其实是一样的,即如果通过

ProtocolDecoderOutput out = (ProtocolDecoderOutput) session.getAttribute(DECODER_OUT);

它们获取的实例是一样的。因此,也就造成两个实例中的ProtocolCodecOutput产生相互干扰的情况。

    我们再来看看为什么两个实例中的AttributeKey为什么会是一样的。

package org.apache.mina.core.session;

import java.io.Serializable;

/**
 * Creates a Key from a class name and an attribute name. The resulting Key will
 * be stored in the session Map.<br>
 * For instance, we can create a 'processor' AttributeKey this way :
 * 
 * <pre>
 * private static final AttributeKey PROCESSOR = new AttributeKey(
 * 	SimpleIoProcessorPool.class, "processor");
 * </pre>
 * 
 * This will create the <b>SimpleIoProcessorPool.processor@7DE45C99</b> key
 * which will be stored in the session map.<br>
 * Such an attributeKey is mainly useful for debug purposes.
 * 
 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
 */
public final class AttributeKey implements Serializable {
    /** The serial version UID */
    private static final long serialVersionUID = -583377473376683096L;

    /** The attribute's name */
    private final String name;

    public AttributeKey(Class<?> source, String name) {
        this.name = source.getName() + '.' + name + '@' + Integer.toHexString(this.hashCode());
    }

    @Override
    public String toString() {
        return name;
    }

    @Override
    public int hashCode() {
        int h = 17 * 37 + ((name == null) ? 0 : name.hashCode());
        return h;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (!(obj instanceof AttributeKey)) {
            return false;
        }

        AttributeKey other = (AttributeKey) obj;

        return name.equals(other.name);
    }
}
    session.getAttrubute(...) 中存储<KEY, VALUE>对的其实是

private static class DefaultIoSessionAttributeMap implements IoSessionAttributeMap {
        private final ConcurrentHashMap<Object, Object> attributes = new ConcurrentHashMap<Object, Object>(4);
		...
}

是一个ConcurrentHashMap。因此,它是通过KEY的hashCode去寻找对象,上述两个实例是一样的,事实上间接说明了它们的hashCode()返回的是一样的值。

    我们看到AttributeKey的hashCode()函数,唯一不一样的地方就只能是name,name是String类型的,其hashCode()计算方法如下:

Open Declaration int java.lang.String.hashCode()


Returns a hash code for this string. The hash code for a String object is computed as 

 s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
 
using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)

从上述String中hashCode()的算法我们可知,只要String的内容一样,它们的hashCode()就是一样的。所以,就有了两个ProtocolCodecFilter中通过session.getAttribute(DECODER_OUT)会拿到同一对象,也就可能产生相互干扰的情况。

    之于相应的解决方法,可以把相应的Filter类抓出来,如ProtocolCodecFitler:

public class MyProtocolCodecFilter extends IoFilterAdapter {
    /** A logger for this class */
    private static final Logger LOGGER = LoggerFactory.getLogger(MyProtocolCodecFilter.class);

    private static final Class<?>[] EMPTY_PARAMS = new Class[0];

    private static final IoBuffer EMPTY_BUFFER = IoBuffer.wrap(new byte[0]);

    private final AttributeKey ENCODER = new AttributeKey(MyProtocolCodecFilter.class, "encoder");

    private final AttributeKey DECODER = new AttributeKey(MyProtocolCodecFilter.class, "decoder");

    private final AttributeKey DECODER_OUT = new AttributeKey(MyProtocolCodecFilter.class, "decoderOut");

    private final AttributeKey ENCODER_OUT = new AttributeKey(MyProtocolCodecFilter.class, "encoderOut");
	
	...
	...
}

调用的时候,由原先的

connector.getFilterChain().addLast("my-codec", new ProtocolCodecFilter(new OwspMessageFactory()));

改成
connector.getFilterChain().addLast("my-codec", new MyProtocolCodecFilter(new OwspMessageFactory()));

注:转载请注明出处 http://blog.csdn.net/oathevil/article/details/37601391

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值