Example usage for java.util.concurrent.locks ReentrantLock ReentrantLock

List of usage examples for java.util.concurrent.locks ReentrantLock ReentrantLock

Introduction

In this page you can find the example usage for java.util.concurrent.locks ReentrantLock ReentrantLock.

Prototype

public ReentrantLock(boolean fair) 

Source Link

Document

Creates an instance of ReentrantLock with the given fairness policy.

Usage

From source file:com.amazon.carbonado.repo.jdbc.JDBCRepository.java

/**
 * @param name name to give repository instance
 * @param isMaster when true, storables in this repository must manage
 * version properties and sequence properties
 * @param dataSource provides JDBC database connections
 * @param catalog optional catalog to search for tables -- actual meaning
 * is database independent/*w  w w  .j  av a  2  s  .c om*/
 * @param schema optional schema to search for tables -- actual meaning is
 * is database independent
 * @param forceStoredSequence tells the repository to use a stored sequence
 * even if the database supports native sequences
 */
@SuppressWarnings("unchecked")
JDBCRepository(AtomicReference<Repository> rootRef, String name, boolean isMaster,
        Iterable<TriggerFactory> triggerFactories, DataSource dataSource, boolean dataSourceClose,
        String catalog, String schema, Integer fetchSize, Map<String, Boolean> autoVersioningMap,
        Map<String, Boolean> suppressReloadMap, String sequenceSelectStatement, boolean forceStoredSequence,
        boolean primaryKeyCheckDisabled, SchemaResolver resolver) throws RepositoryException {
    super(name);
    if (dataSource == null) {
        throw new IllegalArgumentException("DataSource cannot be null");
    }
    mIsMaster = isMaster;
    mTriggerFactories = triggerFactories;
    mRootRef = rootRef;
    mDataSource = dataSource;
    mDataSourceClose = dataSourceClose;
    mCatalog = catalog;
    mSchema = schema;
    mFetchSize = fetchSize;
    mPrimaryKeyCheckDisabled = primaryKeyCheckDisabled;

    mAutoVersioningMap = autoVersioningMap;
    mSuppressReloadMap = suppressReloadMap;

    mResolver = resolver;

    mOpenConnections = new IdentityHashMap<Connection, Object>();
    mOpenConnectionsLock = new ReentrantLock(true);

    // Temporarily set to generic one, in case there's a problem during initialization.
    mExceptionTransformer = new JDBCExceptionTransformer();

    mTxnMgr = new JDBCTransactionManager(this);

    getLog().info("Opening repository \"" + getName() + '"');

    // Test connectivity and get some info on transaction isolation levels.
    Connection con = getConnection();
    try {
        DatabaseMetaData md = con.getMetaData();
        if (md == null || !md.supportsTransactions()) {
            throw new RepositoryException("Database does not support transactions");
        }

        mDatabaseProductName = md.getDatabaseProductName();

        boolean supportsSavepoints;
        try {
            supportsSavepoints = md.supportsSavepoints();
        } catch (AbstractMethodError e) {
            supportsSavepoints = false;
        }

        if (supportsSavepoints) {
            con.setAutoCommit(false);
            // Some JDBC drivers (HSQLDB) lie about their savepoint support.
            try {
                con.setSavepoint();
            } catch (SQLException e) {
                mLog.warn("JDBC driver for " + mDatabaseProductName + " reports supporting savepoints, but it "
                        + "doesn't appear to work: " + e);
                supportsSavepoints = false;
            } finally {
                con.rollback();
                con.setAutoCommit(true);
            }
        }

        mSupportsSavepoints = supportsSavepoints;
        mSupportsSelectForUpdate = md.supportsSelectForUpdate();
        mSupportsScrollInsensitiveReadOnly = md.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);

        mJdbcDefaultIsolationLevel = md.getDefaultTransactionIsolation();
        mDefaultIsolationLevel = mapIsolationLevelFromJdbc(mJdbcDefaultIsolationLevel);

        mReadUncommittedLevel = selectIsolationLevel(md, IsolationLevel.READ_UNCOMMITTED);
        mReadCommittedLevel = selectIsolationLevel(md, IsolationLevel.READ_COMMITTED);
        mRepeatableReadLevel = selectIsolationLevel(md, IsolationLevel.REPEATABLE_READ);
        mSerializableLevel = selectIsolationLevel(md, IsolationLevel.SERIALIZABLE);
    } catch (SQLException e) {
        throw toRepositoryException(e);
    } finally {
        try {
            closeConnection(con);
        } catch (SQLException e) {
            // Don't care.
        }
    }

    mSupportStrategy = JDBCSupportStrategy.createStrategy(this);
    if (forceStoredSequence) {
        mSupportStrategy.setSequenceSelectStatement(null);
    } else if (sequenceSelectStatement != null && sequenceSelectStatement.length() > 0) {
        mSupportStrategy.setSequenceSelectStatement(sequenceSelectStatement);
    }
    mSupportStrategy.setForceStoredSequence(forceStoredSequence);
    mExceptionTransformer = mSupportStrategy.createExceptionTransformer();

    getLog().info("Opened repository \"" + getName() + '"');

    setAutoShutdownEnabled(true);
}

From source file:opendap.threddsHandler.StaticCatalogDispatch.java

public void init(HttpServlet servlet, Element configuration) throws Exception {

    String s;/*from ww  w  .ja  va 2 s .  co m*/

    if (initialized)
        return;

    dispatchServlet = servlet;
    config = configuration;

    Element e;

    e = config.getChild("prefix");
    if (e != null)
        _prefix = e.getTextTrim();

    if (_prefix.equals("/"))
        throw new Exception("Bad Configuration. The <Handler> " + "element that declares "
                + this.getClass().getName() + " MUST provide 1 <_prefix>  "
                + "child element whose value may not be equal to \"/\"");

    if (!_prefix.endsWith("/"))
        _prefix += "/";

    //if(!_prefix.startsWith("/"))
    //    _prefix = "/" + _prefix;

    if (_prefix.startsWith("/"))
        _prefix = _prefix.substring(1, _prefix.length());

    e = config.getChild("useMemoryCache");
    if (e != null) {
        s = e.getTextTrim();
        if (s.equalsIgnoreCase("true")) {
            useMemoryCache = true;
        }
    }

    String ingestTransformFile = null;
    e = config.getChild("ingestTransformFile");
    if (e != null) {
        ingestTransformFile = e.getTextTrim();
    }

    log.debug("Configuration file processing complete.");

    /* USe the generic one for now and if later we want to reuse this code we can pass in another on through the
    config */
    _besApi = new BesApi();

    if (ingestTransformFile == null) {
        ingestTransformFile = ServletUtil.getSystemPath(servlet, "/xsl/threddsCatalogIngest.xsl");
    }

    log.debug("Using ingest transform file: " + ingestTransformFile);

    log.debug("Processing THREDDS catalog.xml file...");

    String contentPath = ServletUtil.getContentPath(servlet);
    CatalogManager.init(contentPath, ingestTransformFile);

    String fileName, pathPrefix, thisUrlPrefix;

    s = "catalog.xml";

    thisUrlPrefix = s.substring(0, s.lastIndexOf(Util.basename(s)));

    s = contentPath + s;
    fileName = "catalog.xml";
    pathPrefix = s.substring(0, s.lastIndexOf(fileName));

    log.debug("Top Level Catalog - pathPrefix: " + pathPrefix);
    log.debug("Top Level Catalog - urlPrefix: " + thisUrlPrefix);
    log.debug("Top Level Catalog - fileName: " + fileName);

    /*
    CatalogManager.addRootCatalog(
        pathPrefix,
        thisUrlPrefix,
        fileName,
        useMemoryCache);
    */

    log.debug("Memory report prior to static thredds catalog ingest: \n{}",
            opendap.coreServlet.Util.getMemoryReport());

    CatalogManager.addCatalog(pathPrefix, thisUrlPrefix, fileName, useMemoryCache);

    log.debug("Memory report post static thredds catalog ingest: \n{}",
            opendap.coreServlet.Util.getMemoryReport());

    log.debug("THREDDS catalog.xml (and children thereof) have been ingested.");

    log.debug("Loading XSLT for thredds presentation views.");

    // Create a lock for use with the thread-unsafe transformer.
    catalogToHtmlTransformLock = new ReentrantLock(true);

    try {
        catalogToHtmlTransformLock.lock();

        // ---------------------
        // Get XSLT document name
        String catalogToHtmlXslt = ServletUtil.getSystemPath(dispatchServlet, catalogToHtmlTransformFile);

        // Build an cache an XSLT transformer for the XSLT document.
        catalogToHtmlTransform = new Transformer(catalogToHtmlXslt);

        log.debug("XSLT file \"" + catalogToHtmlXslt + "\"loaded & parsed. "
                + "Transfrom object created and cached. " + "Transform lock created.");
    } finally {
        catalogToHtmlTransformLock.unlock();
    }

    // Create a lock for use with the thread-unsafe transformer.
    datasetToHtmlTransformLock = new ReentrantLock(true);

    try {
        datasetToHtmlTransformLock.lock();

        // ---------------------
        // Get XSLT document name
        String datasetToHtmlXslt = ServletUtil.getSystemPath(dispatchServlet, datasetToHtmlTransformFile);

        // Build an cache an XSLT transformer for the XSLT document.
        datasetToHtmlTransform = new Transformer(datasetToHtmlXslt);

        log.debug("XSLT file \"" + datasetToHtmlXslt + "\"loaded & parsed. "
                + "Transfrom object created and cached. " + "Transform lock created.");
    } finally {
        datasetToHtmlTransformLock.unlock();
    }

    log.info("Initialized.");
    initialized = true;
}

From source file:com.mirth.connect.donkey.server.channel.Channel.java

/**
 * Start the channel and all of the channel's connectors.
 *//*from w ww.  ja v  a  2 s .  co  m*/
public synchronized void start(Set<Integer> connectorsToStart) throws StartException {
    if (currentState == DeployedState.DEPLOYING || currentState == DeployedState.STOPPED) {
        List<Integer> startedMetaDataIds = new ArrayList<Integer>();

        try {
            ThreadUtils.checkInterruptedStatus();

            updateCurrentState(DeployedState.STARTING);

            /*
             * We can't guarantee the state of the process lock when the channel was stopped or
             * halted, so we just reset it.
             */
            processLock.reset();
            removeContentLock = new ReentrantLock(true);
            dispatchThreads.clear();
            shuttingDown = false;
            stopSourceQueue = false;

            // Remove any items in the queue's buffer because they may be outdated and refresh the queue size.
            sourceQueue.invalidate(true, true);

            channelExecutor = Executors.newCachedThreadPool();

            // start the destination connectors but not the destination queues
            for (DestinationChainProvider chainProvider : destinationChainProviders) {
                for (Integer metaDataId : chainProvider.getMetaDataIds()) {
                    DestinationConnector destinationConnector = chainProvider.getDestinationConnectors()
                            .get(metaDataId);

                    if (destinationConnector.getCurrentState() == DeployedState.STOPPED
                            && (connectorsToStart == null || connectorsToStart.contains(metaDataId))) {
                        startedMetaDataIds.add(metaDataId);
                        destinationConnector.start();
                    }
                }
            }

            ThreadUtils.checkInterruptedStatus();
            try {
                processUnfinishedMessages();
            } catch (InterruptedException e) {
                logger.error("Startup recovery interrupted for channel " + name + " (" + channelId + ")", e);
                throw e;
            } catch (Exception e) {
                Throwable cause;
                if (e instanceof ExecutionException) {
                    cause = e.getCause();
                } else {
                    cause = e;
                }

                logger.error("Startup recovery failed for channel " + name + " (" + channelId + "): "
                        + cause.getMessage(), cause);
            }

            ThreadUtils.checkInterruptedStatus();

            // start the destination queues
            for (Integer metaDataId : startedMetaDataIds) {
                getDestinationConnector(metaDataId).startQueue();
            }

            // Remove any items in the queue's buffer because they may be outdated and refresh the queue size.
            sourceQueue.invalidate(true, true);

            // start up the worker thread that will process queued messages
            if (!sourceConnector.isRespondAfterProcessing()) {
                int processingThreads = ((SourceConnectorPropertiesInterface) sourceConnector
                        .getConnectorProperties()).getSourceConnectorProperties().getProcessingThreads();
                queueThreads.clear();
                for (int i = 1; i <= processingThreads; i++) {
                    Thread queueThread = new Thread(Channel.this);
                    queueThread.setName("Source Queue Thread " + i + " on " + name + " (" + channelId + ")");
                    queueThread.start();
                    queueThreads.put(queueThread.getId(), queueThread);
                }
            }

            if (connectorsToStart == null || connectorsToStart.contains(0)) {
                ThreadUtils.checkInterruptedStatus();
                // start up the source connector
                if (sourceConnector.getCurrentState() == DeployedState.STOPPED) {
                    startedMetaDataIds.add(0);
                    sourceConnector.start();
                }

                updateCurrentState(DeployedState.STARTED);
            } else {
                updateCurrentState(DeployedState.PAUSED);
            }
        } catch (Throwable t) {
            if (t instanceof InterruptedException) {
                throw new StartException("Start channel task for " + name + " (" + channelId
                        + ") terminated by halt notification.", t);
            }
            // If an exception occurred, then attempt to rollback by stopping all the connectors that were started
            try {
                updateCurrentState(DeployedState.STOPPING);
                stop(startedMetaDataIds);
                updateCurrentState(DeployedState.STOPPED);
            } catch (Throwable t2) {
                if (t2 instanceof InterruptedException) {
                    throw new StartException("Start channel task for " + name + " (" + channelId
                            + ") terminated by halt notification.", t);
                }

                updateCurrentState(DeployedState.STOPPED);
            }

            throw new StartException("Failed to start channel " + name + " (" + channelId + ").", t);
        }
    } else {
        logger.warn(
                "Failed to start channel " + name + " (" + channelId + "): The channel is already running.");
    }
}

From source file:org.apereo.portal.portlet.registry.PortletEntityRegistryImpl.java

protected Lock createPortletEntityLock() {
    return new ReentrantLock(true);
}