2

I'm created a proxy class for Jedis, then it can return resource to the pool and mark the broken resource automatically.

public class JedisProxy implements InvocationHandler {

    private final JedisPool jedisPool;

    public JedisProxy(JedisPool pool) {
        this.jedisPool = pool;
    }

    public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {

        Object result;
        Jedis jedis = obtainJedis();
        try {
            result = m.invoke(jedis, args);
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        } catch (Exception e) {
            throw new JedisException("Unexpected proxy invocation exception: " + e.getMessage(), e);
        } finally {
            returnJedis(jedis);
        }
        return result;
    }

    private Jedis obtainJedis() {
        Jedis jedis;
        jedis = jedisPool.getResource();
        return jedis;
    }

    private void returnJedis(Jedis jedis) {
        try {
            if (jedis.isConnected()) {
                jedis.ping();
                jedisPool.returnResource(jedis);
            } else {
                jedisPool.returnBrokenResource(jedis);
            }
        } catch (JedisException e) {
            jedisPool.returnBrokenResource(jedis);
        }
    }
}

then use:

JedisPool p = new JedisPool("10.32.16.19", 6379);
JedisCommands jc = (JedisCommands) Proxy.newProxyInstance(Jedis.class.getClassLoader(), Jedis.class.getInterfaces(), new JedisProxy(pool));

I know that the JedisPool is thread safe.

But is the "jc" object thread safe? Is the proxy object of Proxy.newProxyInstance() thread safe?

I have viewed the source code of Proxy, the proxy object was create by JVM, I'm not familiar with JVM.

Thanks!

4

1 回答 1

0

Proxy.newProxyInstance() 线程的代理对象是否安全?

我不明白这个问题是如何出现的。除了 InvocationHandler 之外,它没有任何状态,并且它是不可变的。问题真的是,你的 InvocationHandler 线程安全吗?

于 2012-07-25T03:45:02.857 回答