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

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

Introduction

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

Prototype

void lockInterruptibly() throws InterruptedException;

Source Link

Document

Acquires the lock unless the current thread is Thread#interrupt interrupted .

Usage

From source file:org.marketcetera.marketdata.core.provider.AbstractMarketDataProvider.java

@Override
public void requestMarketData(MarketDataRequestToken inRequestToken) {
    if (!isRunning()) {
        throw new MarketDataProviderNotAvailable();
    }//from  w  w  w .j av a  2s  . c  o  m
    Set<MarketDataRequestAtom> atoms = explodeRequest(inRequestToken.getRequest());
    totalRequests += atoms.size();
    SLF4JLoggerProxy.debug(this, "Received market data request {}, exploded to {}", //$NON-NLS-1$
            inRequestToken, atoms);
    Lock marketdataRequestLock = marketdataLock.writeLock();
    try {
        marketdataRequestLock.lockInterruptibly();
    } catch (InterruptedException e) {
        org.marketcetera.marketdata.core.Messages.UNABLE_TO_ACQUIRE_LOCK.error(this);
        stop();
        throw new MarketDataRequestFailed(e);
    }
    SLF4JLoggerProxy.trace(this, "Acquired lock"); //$NON-NLS-1$
    try {
        mapRequestToInstruments(inRequestToken);
        for (MarketDataRequestAtom atom : atoms) {
            if (requestsByAtom.containsKey(atom)) {
                SLF4JLoggerProxy.debug(this, "Already requested {}, adding to reference count", atom);
                Instrument snapshotInstrument = instrumentsBySymbol.get(atom.getSymbol());
                if (snapshotInstrument == null) {
                    SLF4JLoggerProxy.warn(this, "Symbol {} not yet mapped, cannot send snapshot",
                            atom.getSymbol());
                } else {
                    Event snapshotEvent = getSnapshot(snapshotInstrument, atom.getContent());
                    if (snapshotEvent instanceof HasEventType) {
                        HasEventType eventTypeSnapshot = (HasEventType) snapshotEvent;
                        eventTypeSnapshot.setEventType(EventType.SNAPSHOT_FINAL);
                    }
                    if (snapshotEvent != null) {
                        SLF4JLoggerProxy.debug(this, "Sending snapshot: {}", snapshotEvent);
                        if (inRequestToken.getSubscriber() != null) {
                            inRequestToken.getSubscriber().publishTo(snapshotEvent);
                        }
                    } else {
                        SLF4JLoggerProxy.debug(this, "No snapshot for {}", atom);
                    }
                }
                requestsByAtom.put(atom, inRequestToken);
                requestsBySymbol.put(atom.getSymbol(), inRequestToken);
            } else {
                Capability requiredCapability = necessaryCapabilities.get(atom.getContent());
                if (requiredCapability == null) {
                    org.marketcetera.marketdata.core.Messages.UNKNOWN_MARKETDATA_CONTENT.error(this,
                            atom.getContent());
                    throw new UnsupportedOperationException(
                            org.marketcetera.marketdata.core.Messages.UNKNOWN_MARKETDATA_CONTENT
                                    .getText(atom.getContent()));
                }
                Set<Capability> capabilities = getCapabilities();
                if (!capabilities.contains(requiredCapability)) {
                    org.marketcetera.marketdata.core.Messages.UNSUPPORTED_MARKETDATA_CONTENT.error(this,
                            atom.getContent(), capabilities.toString());
                    throw new MarketDataRequestFailed(new I18NBoundMessage2P(
                            org.marketcetera.marketdata.core.Messages.UNSUPPORTED_MARKETDATA_CONTENT,
                            atom.getContent(), capabilities.toString()));
                }
                requestsByAtom.put(atom, inRequestToken);
                requestsBySymbol.put(atom.getSymbol(), inRequestToken);
                SLF4JLoggerProxy.debug(this, "Requesting {}", atom);
                doMarketDataRequest(inRequestToken.getRequest(), atom);
            }
        }
    } catch (Exception e) {
        try {
            cancelMarketDataRequest(inRequestToken);
        } catch (Exception ignored) {
        }
        org.marketcetera.marketdata.core.Messages.MARKETDATA_REQUEST_FAILED.warn(this, e);
        if (e instanceof MarketDataException) {
            throw (MarketDataException) e;
        }
        throw new MarketDataRequestFailed(e);
    } finally {
        marketdataRequestLock.unlock();
        SLF4JLoggerProxy.trace(this, "Lock released"); //$NON-NLS-1$
    }
}

From source file:org.marketcetera.marketdata.core.provider.AbstractMarketDataProvider.java

@Override
public void cancelMarketDataRequest(MarketDataRequestToken inRequestToken) {
    // TODO re-exploding the request might cause problems if the request itself changed, better to associate the token ID
    //  with a set of atoms
    Lock cancelLock = marketdataLock.writeLock();
    try {/*w  w w .ja v  a 2 s. c om*/
        cancelLock.lockInterruptibly();
        Set<MarketDataRequestAtom> atoms = explodeRequest(inRequestToken.getRequest());
        for (MarketDataRequestAtom atom : atoms) {
            Collection<MarketDataRequestToken> symbolRequests = requestsByAtom.get(atom);
            if (symbolRequests != null) {
                symbolRequests.remove(inRequestToken);
                if (symbolRequests.isEmpty()) {
                    doCancel(atom);
                }
            }
            Collection<MarketDataRequestToken> requests = requestsBySymbol.get(atom.getSymbol());
            if (requests != null) {
                requests.remove(inRequestToken);
            }
            Instrument mappedInstrument = instrumentsBySymbol.get(atom.getSymbol());
            if (mappedInstrument != null) {
                Collection<MarketDataRequestToken> instrumentRequests = requestsByInstrument
                        .get(mappedInstrument);
                if (instrumentRequests != null) {
                    instrumentRequests.remove(inRequestToken);
                    if (instrumentRequests.isEmpty()) {
                        // no more requests for this instrument, which means this instrument will no longer be updated - clear the cache for it
                        cachedMarketdata.remove(mappedInstrument);
                    }
                }
            }
        }
    } catch (InterruptedException e) {
        org.marketcetera.marketdata.core.Messages.UNABLE_TO_ACQUIRE_LOCK.error(this);
        stop();
    } finally {
        cancelLock.unlock();
    }
}

From source file:org.marketcetera.marketdata.core.provider.AbstractMarketDataProvider.java

@Override
public int getActiveRequests() {
    Lock marketdataQueryLock = marketdataLock.readLock();
    try {/* ww  w.  j a  va  2 s.c om*/
        marketdataQueryLock.lockInterruptibly();
    } catch (InterruptedException e) {
        org.marketcetera.marketdata.core.Messages.UNABLE_TO_ACQUIRE_LOCK.error(this);
        throw new MarketDataRequestFailed(e);
    }
    try {
        return requestsByAtom.size();
    } finally {
        marketdataQueryLock.unlock();
    }
}

From source file:org.marketcetera.marketdata.core.provider.AbstractMarketDataProvider.java

/**
 * Creates a link between the given symbol and the given instrument.
 *
 * @param inSymbol a <code>String</code> value
 * @param inInstrument an <code>Instrument</code> value
 *///www  . j a v a 2  s .com
protected void addSymbolMapping(String inSymbol, Instrument inInstrument) {
    SLF4JLoggerProxy.debug(this, "Adding symbol mapping: {} -> {}", inSymbol, inInstrument);
    Lock symbolMappingLock = marketdataLock.writeLock();
    try {
        symbolMappingLock.lockInterruptibly();
        instrumentsBySymbol.put(inSymbol, inInstrument);
        Collection<MarketDataRequestToken> tokens = requestsBySymbol.get(inSymbol);
        for (MarketDataRequestToken token : tokens) {
            requestsByInstrument.put(inInstrument, token);
        }
    } catch (InterruptedException e) {
        org.marketcetera.marketdata.core.Messages.UNABLE_TO_ACQUIRE_LOCK.error(this);
        stop();
    } finally {
        symbolMappingLock.unlock();
    }
}

From source file:org.springframework.integration.aggregator.AbstractCorrelatingMessageHandler.java

@Override
protected void handleMessageInternal(Message<?> message) throws Exception {
    Object correlationKey = correlationStrategy.getCorrelationKey(message);
    Assert.state(correlationKey != null,
            "Null correlation not allowed.  Maybe the CorrelationStrategy is failing?");

    if (logger.isDebugEnabled()) {
        logger.debug("Handling message with correlationKey [" + correlationKey + "]: " + message);
    }/*ww  w.j a  v  a  2s  .c  o  m*/

    // TODO: INT-1117 - make the lock global?
    Lock lock = this.lockRegistry.obtain(UUIDConverter.getUUID(correlationKey).toString());

    lock.lockInterruptibly();
    try {
        MessageGroup messageGroup = messageStore.getMessageGroup(correlationKey);
        if (this.sequenceAware) {
            messageGroup = new SequenceAwareMessageGroup(messageGroup);
        }

        if (!messageGroup.isComplete() && messageGroup.canAdd(message)) {
            if (logger.isTraceEnabled()) {
                logger.trace("Adding message to group [ " + messageGroup + "]");
            }
            messageGroup = this.store(correlationKey, message);

            if (releaseStrategy.canRelease(messageGroup)) {
                Collection<Message<?>> completedMessages = null;
                try {
                    completedMessages = this.completeGroup(message, correlationKey, messageGroup);
                } finally {
                    // Always clean up even if there was an exception
                    // processing messages
                    this.afterRelease(messageGroup, completedMessages);
                }
            }
        } else {
            discardChannel.send(message);
        }
    } finally {
        lock.unlock();
    }
}

From source file:org.springframework.integration.aggregator.AbstractCorrelatingMessageHandler.java

private void forceComplete(MessageGroup group) {

    Object correlationKey = group.getGroupId();
    // UUIDConverter is no-op if already converted
    Lock lock = this.lockRegistry.obtain(UUIDConverter.getUUID(correlationKey).toString());
    boolean removeGroup = true;
    try {/*from  w ww  .ja v  a  2 s.c  o m*/
        lock.lockInterruptibly();
        try {
            /*
             * Refetch the group because it might have changed while we were waiting on
             * its lock. If the last modified timestamp changed, defer the completion
             * because the selection condition may have changed such that the group
             * would no longer be eligible.
             */
            MessageGroup groupNow = this.messageStore.getMessageGroup(group.getGroupId());
            long lastModifiedNow = groupNow.getLastModified();
            if (group.getLastModified() == lastModifiedNow) {
                if (groupNow.size() > 0) {
                    if (releaseStrategy.canRelease(groupNow)) {
                        this.completeGroup(correlationKey, groupNow);
                    } else {
                        this.expireGroup(correlationKey, groupNow);
                    }
                } else {
                    /*
                     * By default empty groups are removed on the same schedule as non-empty
                     * groups. A longer timeout for empty groups can be enabled by
                     * setting minimumTimeoutForEmptyGroups.
                     */
                    removeGroup = lastModifiedNow <= (System.currentTimeMillis()
                            - this.minimumTimeoutForEmptyGroups);
                    if (removeGroup && logger.isDebugEnabled()) {
                        logger.debug("Removing empty group: " + correlationKey);
                    }
                }
            } else {
                removeGroup = false;
                if (logger.isDebugEnabled()) {
                    logger.debug("Group expiry candidate (" + correlationKey
                            + ") has changed - it may be reconsidered for a future expiration");
                }
            }
        } finally {
            if (removeGroup) {
                this.remove(group);
            }
            lock.unlock();
        }
    } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
        throw new MessagingException("Thread was interrupted while trying to obtain lock");
    }
}

From source file:org.springframework.integration.jdbc.lock.JdbcLockRegistryDifferentClientTests.java

@Test
public void testSecondThreadLoses() throws Exception {

    for (int i = 0; i < 100; i++) {

        final JdbcLockRegistry registry1 = this.registry;
        final JdbcLockRegistry registry2 = this.child.getBean(JdbcLockRegistry.class);
        final Lock lock1 = registry1.obtain("foo");
        final AtomicBoolean locked = new AtomicBoolean();
        final CountDownLatch latch1 = new CountDownLatch(1);
        final CountDownLatch latch2 = new CountDownLatch(1);
        final CountDownLatch latch3 = new CountDownLatch(1);
        lock1.lockInterruptibly();
        Executors.newSingleThreadExecutor().execute(() -> {
            Lock lock2 = registry2.obtain("foo");
            try {
                latch1.countDown();/* w w w. j  a  va2s . c  om*/
                lock2.lockInterruptibly();
                latch2.await(10, TimeUnit.SECONDS);
                locked.set(true);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                lock2.unlock();
                latch3.countDown();
            }
        });
        assertTrue(latch1.await(10, TimeUnit.SECONDS));
        assertFalse(locked.get());
        lock1.unlock();
        latch2.countDown();
        assertTrue(latch3.await(10, TimeUnit.SECONDS));
        assertTrue(locked.get());

    }

}

From source file:org.springframework.integration.jdbc.lock.JdbcLockRegistryDifferentClientTests.java

@Test
public void testBothLock() throws Exception {

    for (int i = 0; i < 100; i++) {

        final JdbcLockRegistry registry1 = this.registry;
        final JdbcLockRegistry registry2 = this.child.getBean(JdbcLockRegistry.class);
        final List<String> locked = new ArrayList<String>();
        final CountDownLatch latch = new CountDownLatch(2);
        ExecutorService pool = Executors.newFixedThreadPool(2);
        pool.execute(() -> {// w ww .  jav a2s  . c  o m
            Lock lock = registry1.obtain("foo");
            try {
                lock.lockInterruptibly();
                locked.add("1");
                latch.countDown();
            } catch (InterruptedException e1) {
                Thread.currentThread().interrupt();
            } finally {
                try {
                    lock.unlock();
                } catch (Exception e2) {
                    // ignore
                }
            }
        });

        pool.execute(() -> {
            Lock lock = registry2.obtain("foo");
            try {
                lock.lockInterruptibly();
                locked.add("2");
                latch.countDown();
            } catch (InterruptedException e1) {
                Thread.currentThread().interrupt();
            } finally {
                try {
                    lock.unlock();
                } catch (Exception e2) {
                    // ignore
                }
            }
        });

        assertTrue(latch.await(10, TimeUnit.SECONDS));
        // eventually they both get the lock and release it
        assertTrue(locked.contains("1"));
        assertTrue(locked.contains("2"));

    }

}

From source file:org.springframework.integration.jdbc.lock.JdbcLockRegistryDifferentClientTests.java

@Test
public void testExclusiveAccess() throws Exception {
    DefaultLockRepository client1 = new DefaultLockRepository(dataSource);
    client1.afterPropertiesSet();// ww w  . jav  a  2 s  .com
    final DefaultLockRepository client2 = new DefaultLockRepository(dataSource);
    client2.afterPropertiesSet();
    Lock lock1 = new JdbcLockRegistry(client1).obtain("foo");
    final BlockingQueue<Integer> data = new LinkedBlockingQueue<Integer>();
    final CountDownLatch latch1 = new CountDownLatch(1);
    lock1.lockInterruptibly();
    Executors.newSingleThreadExecutor().execute(() -> {
        Lock lock2 = new JdbcLockRegistry(client2).obtain("foo");
        try {
            latch1.countDown();
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            lock2.lockInterruptibly();
            stopWatch.stop();
            data.add(4);
            Thread.sleep(10);
            data.add(5);
            Thread.sleep(10);
            data.add(6);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            lock2.unlock();
        }
    });
    assertTrue(latch1.await(10, TimeUnit.SECONDS));
    data.add(1);
    Thread.sleep(1000);
    data.add(2);
    Thread.sleep(1000);
    data.add(3);
    lock1.unlock();
    for (int i = 0; i < 6; i++) {
        Integer integer = data.poll(10, TimeUnit.SECONDS);
        assertNotNull(integer);
        assertEquals(i + 1, integer.intValue());
    }
}

From source file:org.springframework.integration.redis.util.RedisLockRegistryTests.java

@Test
@RedisAvailable//  www  .ja  v  a2 s .c  o m
public void testLockInterruptibly() throws Exception {
    RedisLockRegistry registry = new RedisLockRegistry(this.getConnectionFactoryForTest(), this.registryKey);
    for (int i = 0; i < 10; i++) {
        Lock lock = registry.obtain("foo");
        lock.lockInterruptibly();
        try {
            assertNotNull(TestUtils.getPropertyValue(registry, "hardThreadLocks", ThreadLocal.class).get());
        } finally {
            lock.unlock();
        }
    }
    assertNull(TestUtils.getPropertyValue(registry, "hardThreadLocks", ThreadLocal.class).get());
}