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!