org.skife.jdbi.v2.sqlobject.OnDemandHandleDing Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of jdbi Show documentation
Show all versions of jdbi Show documentation
jDBI is designed to provide convenient tabular data access in
Java(tm). It uses the Java collections framework for query
results, provides a convenient means of externalizing sql
statements, and provides named parameter support for any database
being used.
package org.skife.jdbi.v2.sqlobject;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.IDBI;
import java.util.HashSet;
import java.util.Set;
class OnDemandHandleDing implements HandleDing
{
private final IDBI dbi;
private final ThreadLocal threadDing = new ThreadLocal();
OnDemandHandleDing(IDBI dbi)
{
this.dbi = dbi;
}
public Handle getHandle()
{
if (threadDing.get() == null) {
threadDing.set(new LocalDing(dbi.open()));
}
return threadDing.get().getHandle();
}
public void retain(String name)
{
getHandle(); // need to ensure the local ding has been created as this is called before getHandle sometimes.
threadDing.get().retain(name);
}
public void release(String name)
{
LocalDing ding = threadDing.get();
if (ding == null) {
return;
}
ding.release(name);
}
class LocalDing implements HandleDing {
private final Set retentions = new HashSet();
private final Handle handle;
public LocalDing(Handle handle)
{
this.handle = handle;
}
public Handle getHandle()
{
return handle;
}
public void release(String name)
{
retentions.remove(name);
if (retentions.isEmpty()) {
threadDing.set(null);
handle.close();
}
}
public void retain(String name)
{
retentions.add(name);
}
}
}