All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.skife.jdbi.v2.sqlobject.OnDemandHandleDing Maven / Gradle / Ivy

Go to download

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.

There is a newer version: 2.78
Show newest version
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);
        }

    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy