Use an externally configured DataSource, Flavor, and optionally a shutdown hook.
The shutdown hook may be null if you don't want calls to Builder.close() to attempt
any shutdown. The DataSource and Flavor are mandatory.
189619
@CheckReturnValue
  public static Builder fromPool(Vertx vertx, Pool pool) {
    WorkerExecutor executor = vertx.createSharedWorkerExecutor("DbWorker-" + poolNameCounter.getAndAdd(1), pool.size);
    return new BuilderImpl(executor, () -> {
      try {
        executor.close();
      } catch (Exception e) {
        log.warn("Problem closing database worker executor", e);
      }
      if (pool.poolShutdown != null) {
        pool.poolShutdown.close();
      }
    }, () -> {
      try {
        return pool.dataSource.getConnection();
      } catch (Exception e) {
        throw new DatabaseException("Unable to obtain a connection from DriverManager", e);
      }
    }, new OptionsDefault(pool.flavor));
  }
512556
@Override
	public void stop(BundleContext context) throws Exception {
		final String sourceMethod = "stop"; //$NON-NLS-1$
		boolean isTraceLogging = log.isLoggable(Level.FINER);
		if (isTraceLogging) {
			log.entering(Activator.class.getName(), sourceMethod, new Object[]{context});
		}
		super.stop(context);
		// Shutdown the aggregator instances
		ServiceReference<?>[] refs = context.getServiceReferences(IAggregator.class.getName(), null);
		if (refs != null) {
			for (ServiceReference<?> ref : refs) {
				AggregatorImpl aggr = (AggregatorImpl)context.getService(ref);
				if (aggr != null) {
					try {
						aggr.shutdown();
					} catch (Exception e) {
						if (log.isLoggable(Level.SEVERE)) {
							log.log(Level.SEVERE, e.getMessage(), e);
						}
					}
				}
			}
		}

		for (ServiceRegistration<?> reg : serviceRegistrations) {
			reg.unregister();
		}
		if (executors != null) {
			executors.shutdown();
		}
		this.executors = null;
		Activator.context = null;

		if (isTraceLogging) {
			log.exiting(Activator.class.getName(), sourceMethod);
		}
	}
1103690
@Override
    public void onSourceDrained(int partitionId, String tableName) {
        ExportDataSource source;
        synchronized(m_dataSourcesByPartition) {
            Map<String, ExportDataSource> sources = m_dataSourcesByPartition.get(partitionId);

            if (sources == null) {
                if (!m_removingPartitions.contains(partitionId)) {
                     exportLog.error("Could not find export data sources for partition "
                            + partitionId + ". The export cleanup stream is being discarded.");
                }
                return;
            }

            source = sources.get(tableName);
            if (source == null) {
                exportLog.warn("Could not find export data source for signature " + partitionId +
                        " name " + tableName + ". The export cleanup stream is being discarded.");
                return;
            }

            // Remove source and partition entry if empty
            sources.remove(tableName);
            if (sources.isEmpty()) {
                m_dataSourcesByPartition.remove(partitionId);
                removeMailbox(partitionId);
            }
        }

        //Do closing outside the synchronized block. Do not wait on future since
        // we're invoked from the source's executor thread.
        exportLog.info("Drained on unused partition " + partitionId + ": " + source);
        source.closeAndDelete();
    }
140611
@SuppressWarnings("resource")
    @Override
    @Trivial
    public void close() throws ClassSource_Exception {
        String methodName = "close";
        if ( tc.isEntryEnabled() ) {
            Tr.entry(tc, methodName, getHashText());
        }

        JarFile useJarFile = getJarFile();
        if ( (opens < 0) ||
             ((opens == 0) && (useJarFile != null)) ||
             ((opens > 0) && (useJarFile == null)) ) {

            Tr.warning(tc, "ANNO_CLASSSOURCE_JAR_STATE_BAD", getHashText(), getJarPath(), Integer.valueOf(opens));

            opens = 0;
            useJarFile = clearJarFile();
            if ( useJarFile != null ) {
                try {
                    useJarFile.close(); // throws IOException
                } catch ( IOException e ) {
                    // defect 84235:we are generating multiple Warning/Error messages for each error due to each level reporting them.
                    // Disable the following warning and defer message generation to a higher level, 
                    // preferably the ultimate consumer of the exception.
                    //Tr.warning(tc, "ANNO_CLASSSOURCE_CLOSE5_EXCEPTION", getHashText(), getJarPath());

                    String eMsg = "[ " + getHashText() + " ] Failed to close [ " + getJarPath() + " ]";
                    throw getFactory().wrapIntoClassSourceException(CLASS_NAME, methodName, eMsg, e);
                }
            }

            String eMsg = "[ " + getHashText() + " ] Close with open count [ " + opens + " ]";
            throw getFactory().newClassSourceException(eMsg);
        }

        if ( --opens == 0 ) {
            useJarFile = clearJarFile();

            try {
                useJarFile.close(); // throws IOException
            } catch ( IOException e ) {
                // defect 84235:we are generating multiple Warning/Error messages for each error due to each level reporting them.
                // Disable the following warning and defer message generation to a higher level, 
                // preferably the ultimate consumer of the exception.
                //Tr.warning(tc, "ANNO_CLASSSOURCE_CLOSE5_EXCEPTION", getHashText(), getJarPath());

                String eMsg = "[ " + getHashText() + " ] Failed to close [ " + getJarPath() + " ]";
                throw getFactory().wrapIntoClassSourceException(CLASS_NAME, methodName, eMsg, e);
            }
        }

        if ( tc.isEntryEnabled() ) {
            Tr.exit(tc, methodName, getHashText());
        }
    }
20215
public synchronized void shutdown() {
    // mark this as no longer running
    active = false;

    // close the socket
    try {
      if (socketNode != null) {
        socketNode.close();
        socketNode = null;
      }
    } catch (Exception e) {
      getLogger().info("Excpetion closing socket", e);
      // ignore for now
    }

    // stop the connector
    if (connector != null) {
      connector.interrupted = true;
      connector = null;  // allow gc
    }
    if (advertiseViaMulticastDNS) {
        zeroConf.unadvertise();
    }
  }
1237592
@Override
	public void close() throws Exception {
		if (enterUnlessClosed()) {
			try {
				try {
					// this class' own cleanup logic
					resourceManagerLeaderElectionService.shutdown();
					dispatcher.shutdownNow();
				}
				finally {
					// in any case must we call the parent cleanup logic
					super.close();
				}
			}
			finally {
				exit();
			}
		}
	}
454674
public void shutdownComponent() {
        if (discoveryClient != null) {
            try {
                discoveryClient.shutdown();
                discoveryClient = null;
            } catch (Throwable th) {
                logger.error("Error in shutting down client", th);
            }
        }
    }
71945
@Override
    public void shutdown() {
        final WireMockServer server = this;
        Thread shutdownThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // We have to sleep briefly to finish serving the shutdown request before stopping the server, as
                    // there's no support in Jetty for shutting down after the current request.
                    // See http://stackoverflow.com/questions/4650713
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                server.stop();
            }
        });
        shutdownThread.start();
    }
905758
@Override
	public void dispose() {
		if (this.disposed) {
			return;
		}
		super.dispose();

		// This call will block until all clients that still acquire access to the RocksDB instance have released it,
		// so that we cannot release the native resources while clients are still working with it in parallel.
		rocksDBResourceGuard.close();

		// IMPORTANT: null reference to signal potential async checkpoint workers that the db was disposed, as
		// working on the disposed object results in SEGFAULTS.
		if (db != null) {

			IOUtils.closeQuietly(writeBatchWrapper);

			// Metric collection occurs on a background thread. When this method returns
			// it is guaranteed that thr RocksDB reference has been invalidated
			// and no more metric collection will be attempted against the database.
			if (nativeMetricMonitor != null) {
				nativeMetricMonitor.close();
			}

			List<ColumnFamilyOptions> columnFamilyOptions = new ArrayList<>(kvStateInformation.values().size());

			// RocksDB's native memory management requires that *all* CFs (including default) are closed before the
			// DB is closed. See:
			// https://github.com/facebook/rocksdb/wiki/RocksJava-Basics#opening-a-database-with-column-families
			// Start with default CF ...
			RocksDBOperationUtils.addColumnFamilyOptionsToCloseLater(columnFamilyOptions, defaultColumnFamily);
			IOUtils.closeQuietly(defaultColumnFamily);

			// ... continue with the ones created by Flink...
			for (RocksDbKvStateInfo kvStateInfo : kvStateInformation.values()) {
				RocksDBOperationUtils.addColumnFamilyOptionsToCloseLater(columnFamilyOptions, kvStateInfo.columnFamilyHandle);
				IOUtils.closeQuietly(kvStateInfo.columnFamilyHandle);
			}

			// ... and finally close the DB instance ...
			IOUtils.closeQuietly(db);

			columnFamilyOptions.forEach(IOUtils::closeQuietly);

			IOUtils.closeQuietly(dbOptions);
			IOUtils.closeQuietly(writeOptions);

			ttlCompactFiltersManager.disposeAndClearRegisteredCompactionFactories();

			kvStateInformation.clear();

			cleanInstanceBasePath();
		}
		this.disposed = true;
	}
138761
public static void shutdown()
        throws StartupException
    {
        final Context compCtx;
        try {
            final InitialContext context = new InitialContext();
            compCtx = (javax.naming.Context) context.lookup("java:comp");
        } catch (final NamingException e) {
            throw new StartupException("Could not initialize JNDI", e);
        }
        try {
            Util.unbind(compCtx, "env/" + INamingBinds.RESOURCE_DATASOURCE);
            Util.unbind(compCtx, "env/" + INamingBinds.RESOURCE_DBTYPE);
            Util.unbind(compCtx, "env/" + INamingBinds.RESOURCE_CONFIGPROPERTIES);
            Util.unbind(compCtx, "env/" + INamingBinds.RESOURCE_TRANSMANAG);
        } catch (final NamingException e) {
            throw new StartupException("unbind of the database connection failed", e);
        }
    }
77531
boolean _close() throws SIResourceException
  {
    if (tc.isEntryEnabled()) SibTr.entry(tc, "_close");
    
    boolean closedNow = false;
    
    // Indicate that this connection is closed.
    synchronized (this)
    {
      if (!_closed)
        closedNow = true;
        
      _closed = true;    
    }

    // Ensure that we inform the parent consumer that this
    // bifurcated consumer is closed, so that any messages read
    // by this consumer can be unlocked.
    if (closedNow) {
      try
      {
        _consumerSession.removeBifurcatedConsumer(this);
      }
      catch (SISessionDroppedException e)
      {
  //      RMQSessionDroppedException shouldn't occur so FFDC.
        FFDCFilter.processException(
          e,
          "com.ibm.ws.sib.processor.impl.mqproxy.MQLocalization.getCursor",
          "1:280:1.27",
          this);
  
        SibTr.exception(tc, e);
  
        SIResourceException newE =
          new SIResourceException(
            nls.getFormattedMessage(
              "CONSUMER_CLOSED_ERROR_CWSIP0177",
              new Object[] { _localConsumerPoint.getConsumerManager().getDestination().getName(),
                             _localConsumerPoint.getConsumerManager().getMessageProcessor().getMessagingEngineName()},                
              null));
  
        if (tc.isEntryEnabled())
          SibTr.exit(tc, "getCursor", newE);
  
        throw newE;
      }
    }

    if (tc.isEntryEnabled()) SibTr.exit(tc, "_close", new Boolean(closedNow));
    
    return closedNow;   
  }
157813
@Override
    public void close() {
        if (this.closed.compareAndSet(false, true)) {
            RocksDB db = this.database.get();
            if (db != null) {
                db.close();
                this.database.set(null);
            }

            if (this.writeOptions != null) {
                this.writeOptions.close();
            }

            if (this.databaseOptions != null) {
                this.databaseOptions.close();
            }

            clear(false);
            log.info("{}: Closed.", this.logId);

            Consumer<String> callback = this.closeCallback;
            if (callback != null) {
                Callbacks.invokeSafely(callback, this.id, null);
            }
        }
    }
1211295
private void shutdownDerbyEmbedded() {
        final boolean trace = TraceComponent.isAnyTracingEnabled();
        if (trace && tc.isEntryEnabled())
            Tr.entry(this, tc, "shutdownDerbyEmbedded", classloader, embDerbyRefCount);

        // Shut down Derby embedded if the reference count drops to 0
        if (embDerbyRefCount.remove(classloader) && !embDerbyRefCount.contains(classloader))
            try {
                Class<?> EmbDS = AdapterUtil.forNameWithPriv("org.apache.derby.jdbc.EmbeddedDataSource40", true, classloader);
                DataSource ds = (DataSource) EmbDS.newInstance();
                EmbDS.getMethod("setShutdownDatabase", String.class).invoke(ds, "shutdown");
                ds.getConnection().close();
                if (trace && tc.isEntryEnabled())
                    Tr.exit(this, tc, "shutdownDerbyEmbedded");
            } catch (SQLException x) {
                // expected for shutdown
                if (trace && tc.isEntryEnabled())
                    Tr.exit(this, tc, "shutdownDerbyEmbedded", x.getSQLState() + ' ' + x.getErrorCode() + ':' + x.getMessage());
            } catch (Throwable x) {
                // Work around Derby issue when the JVM is shutting down while Derby shutdown is requested.
                if (trace && tc.isEntryEnabled())
                    Tr.exit(this, tc, "shutdownDerbyEmbedded", x);
            }
        else if (trace && tc.isEntryEnabled())
            Tr.exit(this, tc, "shutdownDerbyEmbedded", false);
    }
452015
async def shutdown(self, container, force=False):
        '''
        
        '''
        p = self._connpool
        self._connpool = []
        self._shutdown = True
        if self._defaultconn:
            p.append(self._defaultconn)
            self._defaultconn = None
        if self._subscribeconn:
            p.append(self._subscribeconn)
            self._subscribeconn = None
        await container.execute_all([self._shutdown_conn(container, o, force)
                                       for o in p])
801602
private void shutDownSqlDrivers() {

        // This manually deregisters JDBC driver, which prevents Tomcat 7 from complaining about memory leaks
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        while (drivers.hasMoreElements()) {
            Driver driver = drivers.nextElement();
            try {
                DriverManager.deregisterDriver(driver);
            } catch (Throwable e) {
                System.out.println(
                    Messages.get().getBundle().key(
                        Messages.ERR_DEREGISTERING_JDBC_DRIVER_1,
                        driver.getClass().getName()));
                e.printStackTrace(System.out);
            }
        }

        try {
            Class<?> cls = Class.forName("com.mysql.jdbc.AbandonedConnectionCleanupThread");
            Method shutdownMethod = (cls == null ? null : cls.getMethod("shutdown"));
            if (shutdownMethod != null) {
                shutdownMethod.invoke(null);
            }
        } catch (Throwable e) {
            System.out.println("Failed to shutdown MySQL connection cleanup thread: " + e.getMessage());
        }
    }
610667
@CheckReturnValue
  public static Builder fromJndi(final Context context, final String lookupKey, Flavor flavor) {
    Options options = new OptionsDefault(flavor);

    return new BuilderImpl(null, () -> {
      DataSource ds;
      try {
        ds = (DataSource) context.lookup(lookupKey);
      } catch (Exception e) {
        throw new DatabaseException("Unable to locate the DataSource in JNDI using key " + lookupKey, e);
      }
      try {
        return ds.getConnection();
      } catch (Exception e) {
        throw new DatabaseException("Unable to obtain a connection from JNDI DataSource " + lookupKey, e);
      }
    }, options);
  }
88321
@Override
    public void shutdown() {
        Throwable shutdownException = null;
        try {
            fire(new ManagerStopping());
        } catch (Exception e) {
            try {
                fireException(e);
            } catch (Exception e2) {
                shutdownException = e2;
            }
        }
        synchronized (this) {
            for (Context context : contexts) {
                context.clearAll();
            }
            contexts.clear();
            extensions.clear();

            runtimeLogger.clear();

            handledThrowables.remove();
        }
        if (shutdownException != null) {
            UncheckedThrow.throwUnchecked(shutdownException);
        }
    }