Skip to content

Instantly share code, notes, and snippets.

@UnquietCode
Last active December 19, 2015 09:49
Show Gist options
  • Save UnquietCode/5936127 to your computer and use it in GitHub Desktop.
Save UnquietCode/5936127 to your computer and use it in GitHub Desktop.
TryWithResource, because sometimes you don't have Java7, and even if you do the actual try-with-resource is somewhat clunky.
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class RedisResource extends TryWithResource<Jedis> {
private final JedisPool pool;
public RedisResource(JedisPool pool) {
this.pool = pool;
}
@Override
protected Jedis getResource() {
return pool.getResource();
}
@Override
protected void returnResource(Jedis jedis) {
pool.returnResource(jedis);
}
}
public class Test {
public static void main(String[] args) {
RedisResource r = new RedisResource(null);
r.doWithResource(new TryWithResource.Action<Jedis, String>() {
public String go(Jedis redis) {
return redis.get("key1");
}
});
}
}
/**
* TryWithResource, because sometimes you don't have Java7, and even if
* you do the actual try-with-resource is somewhat clunky.
*
* @author Ben Fagin
* @version 2013-07-02
*/
public abstract class TryWithResource<_Resource> {
public final <T> T doWithResource(Action<_Resource, T> action) {
final _Resource resource = getResource();
try {
return action.go(resource);
} finally {
returnResource(resource);
}
}
protected abstract _Resource getResource();
protected abstract void returnResource(_Resource resource);
public interface Action<_Resource, _Return> {
public abstract _Return go(_Resource resource);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment