Last active
December 19, 2015 09:49
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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