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() 

Source Link

Document

Creates an instance of ReentrantLock .

Usage

From source file:org.apache.fop.fo.properties.PropertyCache.java

/**
 * Creates a new cache. The "org.apache.fop.fo.properties.use-cache" system
 * property is used to determine whether properties should actually be
 * cached or not. If not, then the {@link #fetch(Object)} method will simply
 * return its argument. To enable the cache, set this property to "true"
 * (case insensitive).//  w w w.  j av a  2 s.c  om
 */
public PropertyCache() {
    boolean useCache;
    try {
        useCache = Boolean.valueOf(System.getProperty("org.apache.fop.fo.properties.use-cache", "true"))
                .booleanValue();
    } catch (SecurityException e) {
        useCache = true;
        LOG.info("Unable to access org.apache.fop.fo.properties.use-cache"
                + " due to security restriction; defaulting to 'true'.");
    }
    if (useCache) {
        this.map = new ConcurrentHashMap<Integer, WeakReference<T>>();
        this.putCounter = new AtomicInteger();
        this.cleanupLock = new ReentrantLock();
        this.hashCodeCollisionCounter = new AtomicInteger();
    } else {
        this.map = null;
        this.putCounter = null;
        this.cleanupLock = null;
        this.hashCodeCollisionCounter = null;
    }
    this.useCache = useCache;
}

From source file:example.pki.VaultPkiConfiguration.java

/**
 * Trivial local implementation suitable for our sample. The underlying {@link Lock}
 * should synchronize on a shared resource like Cluster Leader Election, a Redis Lock,
 * Zookeeper Lock, ...//  w w w  .  j av a  2s .com
 *
 * @return
 */
@Bean
public static SynchronizationProvider synchronizationProvider() {

    final Lock lock = new ReentrantLock();

    return new SynchronizationProvider() {
        @Override
        public Lock getLock() {
            return lock;
        }
    };
}

From source file:org.wso2.carbon.mediation.initializer.AbstractServiceBusAdmin.java

protected Lock getLock() {
    Parameter p = getAxisConfig().getParameter(ServiceBusConstants.SYNAPSE_CONFIG_LOCK);
    if (p != null) {
        return (Lock) p.getValue();
    } else {//  ww w . j a  v  a  2  s  . c o  m
        log.warn(ServiceBusConstants.SYNAPSE_CONFIG_LOCK + " is null, Recreating a new lock");
        Lock lock = new ReentrantLock();
        try {
            getAxisConfig().addParameter(ServiceBusConstants.SYNAPSE_CONFIG_LOCK, lock);
            return lock;
        } catch (AxisFault axisFault) {
            log.error("Error while setting " + ServiceBusConstants.SYNAPSE_CONFIG_LOCK);
        }
    }

    return null;
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.wakeup.WakeupProcessorTest.java

@Test
public void testWakeupProcess() {
    WakeupProcessor processor = new StubWakeupProcessor(new ReentrantLock());
    processor.run();//from www.  ja va2s. co m
    WakeupNotifier notifier = processor.getGCMWakeupNotifier();

    int callCount = ((StubWakeupNotifier) notifier).callCount;

    assertEquals("Non matching call count", 4, callCount);

    WakeupEntityDAO dao = processor.getWakeupEntityDAO();

    List<WakeupEntity> toProcess = dao.poll(10);

    assertTrue("We still have items to process which is not expected", toProcess.isEmpty());

}

From source file:nl.salp.warcraft4j.fileformat.dbc.DbcFile.java

/**
 * Create a new DBC file instance.//from  w w w.  ja  v  a2s.com
 *
 * @param filenameHash       The hash of the DBC filename.
 * @param filename           The name of the DBC file.
 * @param dataReaderSupplier Supplier for the data reader to be used for parsing the DBC file.
 *
 * @throws IllegalArgumentException When the name is invalid.
 */
public DbcFile(long filenameHash, String filename, Supplier<DataReader> dataReaderSupplier)
        throws IllegalArgumentException {
    if (dataReaderSupplier == null) {
        throw new IllegalArgumentException(
                format("Can't create a DbcFile instance for file %d (%s) without a data reader supplier.",
                        filenameHash, filename));
    }
    this.filenameHash = filenameHash;
    this.filename = filename;
    this.dataReaderSupplier = dataReaderSupplier;
    this.parseLock = new ReentrantLock();
}

From source file:org.apache.synapse.transport.nhttp.NhttpSharedOutputBuffer.java

@Deprecated
public NhttpSharedOutputBuffer(final int buffersize, final IOControl ioctrl,
        final ByteBufferAllocator allocator) {
    super(buffersize, allocator);
    Args.notNull(ioctrl, "I/O content control");
    this.ioctrl = ioctrl;
    this.lock = new ReentrantLock();
    this.condition = this.lock.newCondition();
}

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

@Override
public void run() {

    Channel reportingChannel = null;
    try {// ww w .ja v  a  2  s .  c  om
        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:JiraWebSession.java

public JiraWebSession(JiraClient client, String baseUrl) {
    this.client = client;
    this.baseUrl = baseUrl;
    this.secure = baseUrl.startsWith("https"); //$NON-NLS-1$
    this.location = client.getLocation();
    this.authenticationLock = new ReentrantLock();
}

From source file:org.apache.hadoop.net.unix.TestDomainSocketWatcher.java

@Test(timeout = 300000)
public void testStress() throws Exception {
    final int SOCKET_NUM = 250;
    final ReentrantLock lock = new ReentrantLock();
    final DomainSocketWatcher watcher = newDomainSocketWatcher(10000000);
    final ArrayList<DomainSocket[]> pairs = new ArrayList<DomainSocket[]>();
    final AtomicInteger handled = new AtomicInteger(0);

    final Thread adderThread = new Thread(new Runnable() {
        @Override//from  w w w .  j  a v  a 2s. c  o m
        public void run() {
            try {
                for (int i = 0; i < SOCKET_NUM; i++) {
                    DomainSocket pair[] = DomainSocket.socketpair();
                    watcher.add(pair[1], new DomainSocketWatcher.Handler() {
                        @Override
                        public boolean handle(DomainSocket sock) {
                            handled.incrementAndGet();
                            return true;
                        }
                    });
                    lock.lock();
                    try {
                        pairs.add(pair);
                    } finally {
                        lock.unlock();
                    }
                }
            } catch (Throwable e) {
                LOG.error(e);
                throw new RuntimeException(e);
            }
        }
    });

    final Thread removerThread = new Thread(new Runnable() {
        @Override
        public void run() {
            final Random random = new Random();
            try {
                while (handled.get() != SOCKET_NUM) {
                    lock.lock();
                    try {
                        if (!pairs.isEmpty()) {
                            int idx = random.nextInt(pairs.size());
                            DomainSocket pair[] = pairs.remove(idx);
                            if (random.nextBoolean()) {
                                pair[0].close();
                            } else {
                                watcher.remove(pair[1]);
                            }
                        }
                    } finally {
                        lock.unlock();
                    }
                }
            } catch (Throwable e) {
                LOG.error(e);
                throw new RuntimeException(e);
            }
        }
    });

    adderThread.start();
    removerThread.start();
    Uninterruptibles.joinUninterruptibly(adderThread);
    Uninterruptibles.joinUninterruptibly(removerThread);
    watcher.close();
}

From source file:org.gradle.process.internal.DefaultExecHandle.java

DefaultExecHandle(String displayName, File directory, String command, List<String> arguments,
        Map<String, String> environment, OutputStream standardOutput, OutputStream errorOutput,
        InputStream standardInput, List<ExecHandleListener> listeners) {
    this.displayName = displayName;
    this.directory = directory;
    this.command = command;
    this.arguments = arguments;
    this.environment = environment;
    this.standardOutput = standardOutput;
    this.errorOutput = errorOutput;
    this.standardInput = standardInput;
    this.lock = new ReentrantLock();
    this.stateChange = lock.newCondition();
    this.state = ExecHandleState.INIT;
    executor = new DefaultExecutorFactory().create(String.format("Run %s", displayName));
    shutdownHookAction = new ExecHandleShutdownHookAction(this);
    broadcast = new AsyncListenerBroadcast<ExecHandleListener>(ExecHandleListener.class, executor);
    broadcast.addAll(listeners);/*www  .  j av  a2 s  . c  o  m*/
}