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.nuxeo.ecm.core.storage.sql.VCSLockManager.java

/**
 * Creates a lock manager for the given repository.
 * <p>//from   w w  w.  j  a  v a  2  s.co  m
 * The mapper will from then on be only used and closed by the lock manager.
 * <p>
 * {@link #close} must be called when done with the lock manager.
 */
public VCSLockManager(String repositoryName) throws StorageException {
    SQLRepositoryService repositoryService = Framework.getService(SQLRepositoryService.class);
    repository = repositoryService.getRepositoryImpl(repositoryName);
    clusteringEnabled = repository.getRepositoryDescriptor().getClusteringEnabled();
    serializationLock = new ReentrantLock();
    caching = !clusteringEnabled;
    lockCache = caching ? new LRUCache<Serializable, Lock>(CACHE_SIZE) : null;
}

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

public NhttpSharedOutputBuffer(final int buffersize, final ByteBufferAllocator allocator) {
    super(buffersize, allocator);
    this.lock = new ReentrantLock();
    this.condition = this.lock.newCondition();
}

From source file:org.wso2.carbon.apimgt.impl.observers.TenantServiceCreator.java

public void createdConfigurationContext(ConfigurationContext configurationContext) {
    /*String tenantDomain =
        PrivilegedCarbonContext.getCurrentContext(configurationContext).getTenantDomain();
    int tenantId =  PrivilegedCarbonContext.getCurrentContext(configurationContext).getTenantId();*/
    String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    try {/*from w  w  w  .j a v a2 s. co  m*/

        // first check which configuration should be active
        org.wso2.carbon.registry.core.Registry registry = (org.wso2.carbon.registry.core.Registry) PrivilegedCarbonContext
                .getThreadLocalCarbonContext().getRegistry(RegistryType.SYSTEM_CONFIGURATION);

        AxisConfiguration axisConfig = configurationContext.getAxisConfiguration();

        // initialize the lock
        Lock lock = new ReentrantLock();
        axisConfig.addParameter("synapse.config.lock", lock);

        // creates the synapse configuration directory hierarchy if not exists
        // useful at the initial tenant creation
        File tenantAxis2Repo = new File(configurationContext.getAxisConfiguration().getRepository().getFile());
        File synapseConfigsDir = new File(tenantAxis2Repo, "synapse-configs");
        if (!synapseConfigsDir.exists()) {
            if (!synapseConfigsDir.mkdir()) {
                log.fatal("Couldn't create the synapse-config root on the file system "
                        + "for the tenant domain : " + tenantDomain);
                return;
            }
        }

        String synapseConfigsDirLocation = synapseConfigsDir.getAbsolutePath();
        // set the required configuration parameters to initialize the ESB
        //axisConfig.addParameter(SynapseConstants.Axis2Param.SYNAPSE_CONFIG_LOCATION,synapseConfigsDirLocation);

        // init the multiple configuration tracker
        //ConfigurationManager manger = new ConfigurationManager((UserRegistry) registry, configurationContext);
        //manger.init();

        //File synapseConfigDir = new File(synapseConfigsDir,manger.getTracker().getCurrentConfigurationName());
        //File authFailureHandlerSequenceNameFile = new File(synapseConfigsDir + "/" + manger.getTracker().getCurrentConfigurationName() +
        // "/" + MultiXMLConfigurationBuilder.SEQUENCES_DIR + "/" + authFailureHandlerSequenceName + ".xml");
        //Here we will check authfailurehandler sequence exist in synapse artifact. If it is not available we will create
        //sequence synapse configurations by using resource artifacts
        //if (!authFailureHandlerSequenceNameFile.exists()) {
        // createTenantSynapseConfigHierarchy(synapseConfigDir, tenantDomain);
        //}
    } catch (Exception e) {
        log.error("Failed to create Tenant's synapse sequences.", e);
    }
}

From source file:org.proninyaroslav.libretorrent.core.TorrentEngine.java

public TorrentEngine(Context context, TorrentEngineCallback callback) throws Exception {
    this.context = context;
    sync = new ReentrantLock();
    loadTorrentsExec = Executors.newCachedThreadPool();
    this.callback = callback;
}

From source file:org.rhq.core.system.SigarAccessHandler.java

SigarAccessHandler(SigarFactory sigarFactory) {
    this.sigarFactory = sigarFactory;
    sharedSigarLock = new ReentrantLock();
    localSigarLock = new ReentrantLock();
    scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {

        private ThreadFactory defaultThreadFactory = Executors.defaultThreadFactory();

        private AtomicInteger threadCounter = new AtomicInteger(0);

        @Override/*from ww w .ja  v  a  2  s  .  co  m*/
        public Thread newThread(Runnable runnable) {
            Thread thread = defaultThreadFactory.newThread(runnable);
            thread.setName("SigarAccessHandler-" + threadCounter.incrementAndGet());
            // With daemon threads, there is no need to call #shutdown on the executor to let the JVM go down
            thread.setDaemon(true);
            return thread;
        }
    });
    scheduledExecutorService.scheduleWithFixedDelay(new ThresholdChecker(), 1, 5, MINUTES);
    localSigarInstancesCount = 0;
    closed = false;
}

From source file:org.apache.openjpa.event.TCPRemoteCommitProvider.java

public TCPRemoteCommitProvider() throws UnknownHostException {
    // obtain a unique ID.
    synchronized (TCPRemoteCommitProvider.class) {
        _id = s_idSequence++;//from   ww  w.  j  a  va2  s  .  c o m
    }

    // cache the local IP address.
    _localhost = InetAddress.getLocalHost().getAddress();
    _addressesLock = new ReentrantLock();
    setNumBroadcastThreads(2);
}

From source file:com.lonepulse.zombielink.processor.AsyncEndpointTest.java

/**
 * <p>Tests asynchronous request execution with @{@link Async} and 
 * {@link AsyncHandler#onFailure(HttpResponse)}.</p>
 *  /*from   w  ww. jav  a2  s .c o m*/
 * @since 1.3.0
 */
@Test
public final void testAsyncFailure() throws InterruptedException {

    String subpath = "/asyncfailure", body = "hello";

    stubFor(get(urlEqualTo(subpath)).willReturn(aResponse().withStatus(403).withBody(body)));

    final Object[] content = new Object[1];

    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();

    asyncEndpoint.asyncFailure(new AsyncHandler<String>() {

        @Override
        public void onSuccess(HttpResponse httpResponse, String e) {
        }

        @Override
        public void onFailure(HttpResponse httpResponse) {

            lock.lock();

            content[0] = httpResponse;
            condition.signal();

            lock.unlock();
        }
    });

    lock.lock();
    condition.await();
    lock.unlock();

    verify(getRequestedFor(urlEqualTo(subpath)));

    assertTrue(content[0] != null);
}

From source file:ch.algotrader.service.ib.IBNativeOrderServiceImpl.java

public IBNativeOrderServiceImpl(final IBSession iBSession, final AutoIncrementIdGenerator orderIdGenerator,
        final OrderBook orderBook, final IBExecutions iBExecutions,
        final IBOrderMessageFactory iBOrderMessageFactory,
        final OrderPersistenceService orderPersistenceService, final OrderDao orderDao,
        final CommonConfig commonConfig) {

    Validate.notNull(iBSession, "IBSession is null");
    Validate.notNull(orderIdGenerator, "AutoIncrementIdGenerator is null");
    Validate.notNull(orderBook, "OpenOrderRegistry is null");
    Validate.notNull(iBExecutions, "IBExecutions is null");
    Validate.notNull(iBOrderMessageFactory, "IBOrderMessageFactory is null");
    Validate.notNull(orderPersistenceService, "OrderPersistenceService is null");
    Validate.notNull(orderDao, "OrderDao is null");
    Validate.notNull(commonConfig, "CommonConfig is null");

    this.iBSession = iBSession;
    this.orderIdGenerator = orderIdGenerator;
    this.orderBook = orderBook;
    this.iBExecutions = iBExecutions;
    this.iBOrderMessageFactory = iBOrderMessageFactory;
    this.orderPersistenceService = orderPersistenceService;
    this.orderDao = orderDao;
    this.commonConfig = commonConfig;
    this.lock = new ReentrantLock();
    this.firstTime = new AtomicBoolean(false);
}

From source file:com.espertech.esper.regression.view.TestMultithreadedTimeWin.java

private void setUp(int numSymbols, int numThreads, int numEvents, double timeWindowSize) {
    EPServiceProvider epService = EPServiceProviderManager
            .getDefaultProvider(SupportConfigFactory.getConfiguration());
    epService.initialize();//from  w  ww  . j  a v a2s  . c o m

    // Create a statement for N number of symbols, each it's own listener
    String symbols[] = new String[numSymbols];
    listeners = new ResultUpdateListener[symbols.length];
    for (int i = 0; i < symbols.length; i++) {
        symbols[i] = "S" + i;
        String viewExpr = "select symbol, sum(volume) as sumVol " + "from "
                + SupportMarketDataBean.class.getName() + "(symbol='" + symbols[i] + "').win:time("
                + timeWindowSize + ")";
        EPStatement testStmt = epService.getEPAdministrator().createEPL(viewExpr);
        listeners[i] = new ResultUpdateListener();
        testStmt.addListener(listeners[i]);
    }

    // Create threads to send events
    threads = new Thread[numThreads];
    TimeWinRunnable[] runnables = new TimeWinRunnable[threads.length];
    ReentrantLock lock = new ReentrantLock();
    for (int i = 0; i < threads.length; i++) {
        runnables[i] = new TimeWinRunnable(i, epService.getEPRuntime(), lock, symbols, numEvents);
        threads[i] = new Thread(runnables[i]);
    }
}

From source file:org.rifidi.edge.epcglobal.aleread.wrappers.RifidiECSpec.java

/**
 * Constructor.//w ww. j av  a2s . c om
 * 
 * @param name
 * @param spec
 * @param esper
 * @param rifidiBoundarySpec
 * @param readers
 * @param primarykeys
 * @param reports
 * @throws InvalidURIExceptionResponse
 * @throws ECSpecValidationExceptionResponse
 */
public RifidiECSpec(final String name, final ECSpec spec, final EPServiceProvider esper,
        final RifidiBoundarySpec rifidiBoundarySpec, final Collection<String> readers,
        final Collection<String> primarykeys, final Collection<RifidiReport> reports) {
    this.startLock = new ReentrantLock();
    this.rifidiBoundarySpec = rifidiBoundarySpec;
    this.spec = spec;
    this.name = name;
    this.esper = esper;
    this.readers = new HashSet<String>();
    this.readers.addAll(readers);
    // configure the report sender
    this.sender = new ReportSender(reports, name, spec);

    // collect the primary keys
    this.primarykeys = new HashSet<String>();
    this.primarykeys.addAll(primarykeys);
    if (this.primarykeys.isEmpty()) {
        this.primarykeys.add("epc");
    }
    this.subscriptionURIs = new CopyOnWriteArrayList<String>();

    startStatementControllers = new ArrayList<StatementController>();
    stopStatementControllers = new ArrayList<StatementController>();
    //      collectionStatements = new ArrayList<EPStatement>();
    //      collectionStatements.add();
    this.esper.getEPAdministrator()
            .createEPL("insert into ecspec_" + name
                    + " select * from ReadCycle[select * from tags] where readerID in ("
                    + assembleLogicalReader(this.readers) + ") ");
    // add a timer if we got triggers
    if (rifidiBoundarySpec.getStartTriggers().size() != 0 || rifidiBoundarySpec.getStopTriggers() != null) {
        timer = new Timer(rifidiBoundarySpec.getStartTriggers(), rifidiBoundarySpec.getStopTriggers(),
                this.esper);
    }
    // TODO: When data available needs to be added ASAP!!!
    if (rifidiBoundarySpec.isWhenDataAvailable()) {
        logger.fatal("'When data available' not yet implemented!");
    }
    if (rifidiBoundarySpec.getDuration() > 0) {
        logger.debug("Initializing duration timing with duration=" + rifidiBoundarySpec.getDuration());
        DurationTimingStatement durationTimingStatement = new DurationTimingStatement(
                this.esper.getEPAdministrator(), "ecspec_" + name, rifidiBoundarySpec.getDuration(),
                this.primarykeys);
        durationTimingStatement.registerSignalListener(this);
        stopStatementControllers.add(durationTimingStatement);
    }
    // if (rifidiBoundarySpec.getStableSetInterval() > 0) {
    // logger
    // .debug("Initializing 'stable set interval' timing with interval="
    // + rifidiBoundarySpec.getStableSetInterval());
    // StableSetTimingStatement stableSetTimingStatement = new
    // StableSetTimingStatement(
    // esper.getEPAdministrator(), rifidiBoundarySpec
    // .getStableSetInterval(), primarykeys);
    // stableSetTimingStatement.registerSignalListener(this);
    // stopStatementControllers.add(stableSetTimingStatement);
    // }
    // if (rifidiBoundarySpec.getStopTriggers().size() > 0) {
    // // TODO: create triggers
    // StopEventTimingStatement stopEventTimingStatement = new
    // StopEventTimingStatement(
    // esper.getEPAdministrator(), primarykeys);
    // stopEventTimingStatement.registerSignalListener(this);
    // stopStatementControllers.add(stopEventTimingStatement);
    // }
    if (rifidiBoundarySpec.getStartTriggers().size() > 0) {
        instantStart = false;
        StartEventStatement startEventStatement = new StartEventStatement(this.esper.getEPAdministrator());
        startEventStatement.registerSignalListener(this);
        startEventStatement.start();
        startStatementControllers.add(startEventStatement);
    }
    if (rifidiBoundarySpec.getRepeatInterval() > 0) {
        IntervalTimingStatement intervalTimingStatement = new IntervalTimingStatement(
                this.esper.getEPAdministrator(), rifidiBoundarySpec.getRepeatInterval());
        intervalTimingStatement.registerSignalListener(this);
        startStatementControllers.add(intervalTimingStatement);
    }
}