Example usage for java.util.concurrent.locks Lock lock

List of usage examples for java.util.concurrent.locks Lock lock

Introduction

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

Prototype

lock

Source Link

Usage

From source file:edu.internet2.middleware.shibboleth.common.config.BaseService.java

/** {@inheritDoc} */
public void destroy() throws ServiceException {
    Lock writeLock = getReadWriteLock().writeLock();
    writeLock.lock();
    isDestroyed = true;/*from w w  w .  ja  v a2 s  . co  m*/
    serviceContext = null;
    serviceConfigurations.clear();
    setInitialized(false);
    writeLock.unlock();
    serviceContextRWLock = null;
}

From source file:org.springframework.integration.metadata.PropertiesPersistingMetadataStore.java

@Override
public boolean replace(String key, String oldValue, String newValue) {
    Assert.notNull(key, "'key' cannot be null");
    Assert.notNull(oldValue, "'oldValue' cannot be null");
    Assert.notNull(newValue, "'newValue' cannot be null");
    Lock lock = this.lockRegistry.obtain(key);
    lock.lock();
    try {//from w w  w .ja  v  a 2s .c  om
        String property = this.metadata.getProperty(key);
        if (oldValue.equals(property)) {
            this.metadata.setProperty(key, newValue);
            this.dirty = true;
            return true;
        } else {
            return false;
        }
    } finally {
        lock.unlock();
    }
}

From source file:fm.last.moji.impl.MojiFileImpl.java

@Override
public InputStream getInputStream() throws IOException {
    log.debug("getInputStream() : {}", this);
    InputStream inputStream = null;
    try {//from w  w  w  .ja va 2  s . c  om
        Lock readLock = lock.readLock();
        readLock.lock();
        GetInputStreamCommand command = new GetInputStreamCommand(key, domain, httpFactory, readLock);
        executor.executeCommand(command);
        inputStream = command.getInputStream();
        log.debug("getInputStream() -> {}", inputStream);
    } catch (Throwable e) {
        unlockQuietly(lock.readLock());
        IOUtils.closeQuietly(inputStream);
        if (e instanceof IOException) {
            throw (IOException) e;
        } else {
            throw new RuntimeException(e);
        }
    }
    // calling close will release the lock
    return inputStream;
}

From source file:fm.last.moji.impl.MojiFileImpl.java

@Override
public OutputStream getOutputStream() throws IOException {
    log.debug("getOutputStream() : {}", this);
    OutputStream outputStream = null;
    try {//from  w ww .j  a va 2  s.c  o  m
        Lock writeLock = lock.writeLock();
        writeLock.lock();
        GetOutputStreamCommand command = new GetOutputStreamCommand(trackerFactory, httpFactory, key, domain,
                storageClass, writeLock);
        executor.executeCommand(command);
        outputStream = command.getOutputStream();
        log.debug("getOutputStream() -> {}", outputStream);
    } catch (Throwable e) {
        unlockQuietly(lock.writeLock());
        IOUtils.closeQuietly(outputStream);
        if (e instanceof IOException) {
            throw (IOException) e;
        } else {
            throw new RuntimeException(e);
        }
    }
    // calling close will release the lock
    return outputStream;
}

From source file:de.taimos.daemon.spring.SpringDaemonAdapter.java

@Override
public final void doStart() throws Exception {
    super.doStart();
    try {//from www  . j  a  v  a  2 s. c  o  m
        this.doBeforeSpringStart();
    } catch (Exception e) {
        throw new RuntimeException("Before spring failed", e);
    }

    Lock writeLock = this.rwLock.writeLock();
    AbstractXmlApplicationContext ctx = null;
    try {
        writeLock.lock();
        if (this.context.get() != null) {
            throw new RuntimeException("Already started");
        }
        ctx = this.createSpringContext();
        String[] profiles = System.getProperty(Configuration.PROFILES, Configuration.PROFILES_PRODUCTION)
                .split(",");
        ctx.getEnvironment().setActiveProfiles(profiles);

        final PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        configurer.setProperties(DaemonStarter.getDaemonProperties());
        ctx.addBeanFactoryPostProcessor(configurer);

        ctx.setConfigLocation(this.getSpringResource());
        ctx.refresh();
    } catch (Exception e) {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e1) {
                this.logger.warn("Failed to close context", e1);
            }
            ctx = null;
        }
        throw new RuntimeException("Spring context failed", e);
    } finally {
        if (ctx != null) {
            this.context.set(ctx);
        }
        writeLock.unlock();
    }

    try {
        this.doAfterSpringStart();
    } catch (Exception e) {
        throw new RuntimeException("After spring failed", e);
    }
}

From source file:info.pancancer.arch3.worker.WorkerHeartbeat.java

@Override
public void run() {

    Channel reportingChannel = null;
    try {//from w ww . ja  v  a 2  s . c o  m
        try {
            reportingChannel = Utilities.setupExchange(settings, this.queueName);
        } catch (IOException | TimeoutException | AlreadyClosedException e) {
            LOG.error("Exception caught! Queue channel could not be opened, waiting. Exception is: "
                    + e.getMessage(), e);
            // retry after a minute, do not die simply because the launcher is unavailable, it may come back
            Thread.sleep(Base.ONE_MINUTE_IN_MILLISECONDS);
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        LOG.info("Caught interrupt signal, heartbeat shutting down.", e);
        return;
    }

    LOG.info("starting heartbeat thread, will send heartbeat message ever " + secondsDelay + " seconds.");
    while (!Thread.interrupted()) {
        // byte[] stdOut = this.getMessageBody().getBytes(StandardCharsets.UTF_8);
        try {
            try {
                Status heartbeatStatus = new Status();
                heartbeatStatus.setJobUuid(this.jobUuid);
                heartbeatStatus.setMessage("job is running; IP address: " + networkID);
                heartbeatStatus.setState(StatusState.RUNNING);
                heartbeatStatus.setType(Utilities.JOB_MESSAGE_TYPE);
                heartbeatStatus.setVmUuid(this.vmUuid);
                heartbeatStatus.setIpAddress(networkID);

                // String stdOut = this.statusSource.getStdOut();
                Lock lock = new ReentrantLock();
                lock.lock();
                String stdOut = this.statusSource.getStdOut(stdoutSnipSize);
                String stdErr = this.statusSource.getStdErr();
                lock.unlock();
                heartbeatStatus.setStdout(stdOut);
                heartbeatStatus.setStderr(stdErr);
                String heartBeatMessage = heartbeatStatus.toJSON();
                LOG.debug("Sending heartbeat message to " + queueName + ", with body: " + heartBeatMessage);
                reportingChannel.basicPublish(queueName, queueName, MessageProperties.PERSISTENT_TEXT_PLAIN,
                        heartBeatMessage.getBytes(StandardCharsets.UTF_8));
                reportingChannel.waitForConfirms();

                Thread.sleep((long) (secondsDelay * MILLISECONDS_PER_SECOND));
            } catch (IOException | AlreadyClosedException e) {
                LOG.error("IOException caught! Message may not have been published. Exception is: "
                        + e.getMessage(), e);
                // retry after a minute, do not die simply because the launcher is unavailable, it may come back
                Thread.sleep(Base.ONE_MINUTE_IN_MILLISECONDS);
            }
        } catch (InterruptedException e) {
            LOG.info("Heartbeat shutting down.");
            if (reportingChannel.getConnection().isOpen()) {
                try {
                    reportingChannel.getConnection().close();
                } catch (IOException e1) {
                    LOG.error("Error closing reportingChannel connection: " + e1.getMessage(), e1);
                }
            }
            if (reportingChannel.isOpen()) {
                try {
                    reportingChannel.close();
                } catch (IOException e1) {
                    LOG.error("Error (IOException) closing reportingChannel: " + e1.getMessage(), e1);
                } catch (TimeoutException e1) {
                    LOG.error("Error (TimeoutException) closing reportingChannel: " + e1.getMessage(), e1);
                }
            }
            LOG.debug("reporting channel open: " + reportingChannel.isOpen());
            LOG.debug("reporting channel connection open: " + reportingChannel.getConnection().isOpen());

            Thread.currentThread().interrupt();
        }
    }
}

From source file:com.jayway.jaxrs.hateoas.DefaultHateoasContext.java

/**
 * Checks if the specified class has been registered. If not add the class to the set mapping
 * registred classes./*www .j a v  a  2 s  .c o m*/
 *
 * @param clazz the class to check
 * @return <code>true</code> if the class has already been registered,
 *         <code>false</code> otherwise.
 */
public boolean isInitialized(Class<?> clazz) {
    Lock readLock = LOCK.readLock();
    try {
        readLock.lock();
        if (initializedClasses.contains(clazz)) {
            return true;
        }
    } finally {
        readLock.unlock();
    }

    Lock writeLock = LOCK.writeLock();
    try {
        writeLock.lock();
        if (!initializedClasses.contains(clazz)) { // check again - things might have changed
            initializedClasses.add(clazz);
            return false;
        }
    } finally {
        writeLock.unlock();
    }

    return true;
}

From source file:com.enonic.cms.business.portal.image.ImageServiceImpl.java

public ImageResponse process(ImageRequest imageRequest) {
    Preconditions.checkNotNull(imageRequest, "imageRequest cannot be null");

    final ImageRequestTrace imageRequestTrace = livePortalTraceService.getCurrentImageRequestTrace();

    String blobKey = getBlobKey(imageRequest);
    if (blobKey == null) {
        return ImageResponse.notFound();
    }/*from  w  ww .j a  v a 2  s .c  o m*/

    imageRequest.setBlobKey(blobKey);

    final Lock locker = concurrencyLock.getLock(imageRequest.getCacheKey());

    try {
        locker.lock();

        ImageResponse res = imageCache.get(imageRequest);
        if (res != null) {
            ImageRequestTracer.traceImageResponse(imageRequestTrace, res);
            ImageRequestTracer.traceUsedCachedResult(imageRequestTrace, true);
            return res;
        }

        try {
            res = doProcess(imageRequest);
            ImageRequestTracer.traceImageResponse(imageRequestTrace, res);
            ImageRequestTracer.traceUsedCachedResult(imageRequestTrace, false);
            return res;
        } catch (Exception e) {
            throw new ImageProcessorException("Failed to process image: " + e.getMessage(), e);
        }
    } finally {
        locker.unlock();
    }
}

From source file:edu.internet2.middleware.shibboleth.common.config.BaseService.java

/**
 * Loads the service context.//w  ww  .ja  v  a  2s  .c om
 * 
 * @throws ServiceException thrown if the configuration for this service could not be loaded
 */
protected void loadContext() throws ServiceException {
    log.info("Loading new configuration for service {}", getId());

    if (serviceConfigurations == null || serviceConfigurations.isEmpty()) {
        setInitialized(true);
        return;
    }

    GenericApplicationContext newServiceContext = new GenericApplicationContext(getApplicationContext());
    newServiceContext.setDisplayName("ApplicationContext:" + getId());
    Lock writeLock = getReadWriteLock().writeLock();
    writeLock.lock();
    try {
        SpringConfigurationUtils.populateRegistry(newServiceContext, getServiceConfigurations());
        newServiceContext.refresh();

        GenericApplicationContext replacedServiceContext = serviceContext;
        onNewContextCreated(newServiceContext);
        setServiceContext(newServiceContext);
        setInitialized(true);
        if (replacedServiceContext != null) {
            replacedServiceContext.close();
        }
        log.info("{} service loaded new configuration", getId());
    } catch (Throwable e) {
        // Here we catch all the other exceptions thrown by Spring when it starts up the context
        setInitialized(false);
        Throwable rootCause = e;
        while (rootCause.getCause() != null) {
            rootCause = rootCause.getCause();
        }
        log.error("Configuration was not loaded for " + getId()
                + " service, error creating components.  The root cause of this error was: "
                + rootCause.getClass().getCanonicalName() + ": " + rootCause.getMessage());
        log.trace("Full stacktrace is: ", e);
        throw new ServiceException(
                "Configuration was not loaded for " + getId() + " service, error creating components.",
                rootCause);
    } finally {
        writeLock.unlock();
    }
}

From source file:com.callidusrobotics.droptables.configuration.MongoFactory.java

/**
 * Generates a connection wrapper using the read-write credentials.
 *
 * @param env//ww w .ja v  a  2  s.c om
 *          The application's environment
 * @return The connection wrapper, never null
 * @throws UnknownHostException
 * @see #buildReadWriteClient(Environment)
 */
public Datastore buildReadWriteDatastore(Environment env) throws UnknownHostException {
    if (rwDatastore != null) {
        return rwDatastore;
    }

    Lock lock = locks[LockFlags.DATASTORE.ordinal()];
    lock.lock();

    try {
        if (rwDatastore == null) {
            rwDatastore = morphia.createDatastore(buildReadWriteClient(env), dbName);
        }
    } finally {
        lock.unlock();
    }

    return rwDatastore;
}