List of usage examples for java.util.concurrent.locks ReentrantLock ReentrantLock
public ReentrantLock()
From source file:com.amazonaws.mobile.client.AWSMobileClient.java
/** * Constructor invoked by getInstance./* www .j ava 2 s. com*/ * * @throws AssertionError when this is called with context more than once. */ private AWSMobileClient() { if (singleton != null) { throw new AssertionError(); } this.clientMap = new LinkedHashMap<Class<? extends AWSConfigurable>, AWSConfigurable>(); userpoolsLoginKey = ""; mWaitForSignInLock = new ReentrantLock(); mFederatedLoginsMap = new HashMap<String, String>(); listeners = new ArrayList<UserStateListener>(); showSignInLockObject = new Object(); federateWithCognitoIdentityLockObject = new Object(); showSignInWaitLatch = new CountDownLatch(1); initLockObject = new Object(); }
From source file:com.thoughtworks.studios.journey.JourneyService.java
private static Lock getWritingLock(String ns) { Lock lock = new ReentrantLock(); Lock existingLock = writingLocks.putIfAbsent(ns, lock); if (existingLock != null) { lock = existingLock;/*from w ww.j av a 2 s.c o m*/ } return lock; }
From source file:org.apache.lens.driver.hive.HiveDriver.java
/** * Instantiates a new hive driver./*from w ww . ja v a2 s . c o m*/ * * @throws LensException the lens exception */ public HiveDriver() throws LensException { this.sessionLock = new ReentrantLock(); lensToHiveSession = new HashMap<>(); opHandleToSession = new ConcurrentHashMap<>(); orphanedHiveSessions = new ConcurrentLinkedQueue<>(); resourcesAddedForSession = new HashMap<>(); connectionExpiryThread.setDaemon(true); connectionExpiryThread.setName("HiveDriver-ConnectionExpiryThread"); connectionExpiryThread.start(); driverListeners = new ArrayList<LensEventListener<DriverEvent>>(); log.info("Hive driver inited"); }
From source file:com.cyberway.issue.crawler.framework.CrawlController.java
/** * Starting from nothing, set up CrawlController and associated * classes to be ready for a first crawl. * * @param sH Settings handler.// www . ja v a 2 s. c om * @throws InitializationException */ public void initialize(SettingsHandler sH) throws InitializationException { sendCrawlStateChangeEvent(PREPARING, CrawlJob.STATUS_PREPARING); this.singleThreadLock = new ReentrantLock(); this.settingsHandler = sH; installThreadContextSettingsHandler(); this.order = settingsHandler.getOrder(); this.order.setController(this); this.bigmaps = new Hashtable<String, CachedBdbMap<?, ?>>(); sExit = ""; this.manifest = new StringBuffer(); String onFailMessage = ""; try { onFailMessage = "You must set the User-Agent and From HTTP" + " header values to acceptable strings. \n" + " User-Agent: [software-name](+[info-url])[misc]\n" + " From: [email-address]\n"; order.checkUserAgentAndFrom(); onFailMessage = "Unable to setup disk"; if (disk == null) { setupDisk(); } onFailMessage = "Unable to create log file(s)"; setupLogs(); // Figure if we're to do a checkpoint restore. If so, get the // checkpointRecover instance and then put into place the old bdb // log files. If any of the log files already exist in target state // diretory, WE DO NOT OVERWRITE (Makes for faster recovery). // CrawlController checkpoint recovery code manages restoration of // the old StatisticsTracker, any BigMaps used by the Crawler and // the moving of bdb log files into place only. Other objects // interested in recovery need to ask if // CrawlController#isCheckpointRecover is set to figure if in // recovery and then take appropriate recovery action // (These objects can call CrawlController#getCheckpointRecover // to get the directory that might hold files/objects dropped // checkpointing). Such objects will need to use a technique other // than object serialization restoring settings because they'll // have already been constructed when comes time for object to ask // if its to recover itself. See ARCWriterProcessor for example. onFailMessage = "Unable to test/run checkpoint recover"; this.checkpointRecover = getCheckpointRecover(); if (this.checkpointRecover == null) { this.checkpointer = new Checkpointer(this, this.checkpointsDisk); } else { setupCheckpointRecover(); } onFailMessage = "Unable to setup bdb environment."; setupBdb(); onFailMessage = "Unable to setup statistics"; setupStatTracking(); onFailMessage = "Unable to setup crawl modules"; setupCrawlModules(); } catch (Exception e) { String tmp = "On crawl: " + settingsHandler.getSettingsObject(null).getName() + " " + onFailMessage; LOGGER.log(Level.SEVERE, tmp, e); throw new InitializationException(tmp, e); } // force creation of DNS Cache now -- avoids CacheCleaner in toe-threads group // also cap size at 1 (we never wanta cached value; 0 is non-operative) Lookup.getDefaultCache(DClass.IN).setMaxEntries(1); //dns.getRecords("localhost", Type.A, DClass.IN); setupToePool(); setThresholds(); reserveMemory = new LinkedList<char[]>(); for (int i = 1; i < RESERVE_BLOCKS; i++) { reserveMemory.add(new char[RESERVE_BLOCK_SIZE]); } }
From source file:org.archive.crawler.framework.CrawlController.java
/** * Starting from nothing, set up CrawlController and associated * classes to be ready for a first crawl. * * @param sH Settings handler.//from w ww .j ava 2s . c om * @throws InitializationException */ public void initialize(SettingsHandler sH) throws InitializationException { sendCrawlStateChangeEvent(PREPARING, CrawlJob.STATUS_PREPARING); this.singleThreadLock = new ReentrantLock(); this.settingsHandler = sH; installThreadContextSettingsHandler(); this.order = settingsHandler.getOrder(); this.order.setController(this); this.bigmaps = new Hashtable<String, ObjectIdentityCache<?, ?>>(); sExit = ""; this.manifest = new StringBuffer(); String onFailMessage = ""; try { onFailMessage = "You must set the User-Agent and From HTTP" + " header values to acceptable strings. \n" + " User-Agent: [software-name](+[info-url])[misc]\n" + " From: [email-address]\n"; order.checkUserAgentAndFrom(); onFailMessage = "Unable to setup disk"; if (disk == null) { setupDisk(); } onFailMessage = "Unable to create log file(s)"; setupLogs(); // Figure if we're to do a checkpoint restore. If so, get the // checkpointRecover instance and then put into place the old bdb // log files. If any of the log files already exist in target state // diretory, WE DO NOT OVERWRITE (Makes for faster recovery). // CrawlController checkpoint recovery code manages restoration of // the old StatisticsTracker, any BigMaps used by the Crawler and // the moving of bdb log files into place only. Other objects // interested in recovery need to ask if // CrawlController#isCheckpointRecover is set to figure if in // recovery and then take appropriate recovery action // (These objects can call CrawlController#getCheckpointRecover // to get the directory that might hold files/objects dropped // checkpointing). Such objects will need to use a technique other // than object serialization restoring settings because they'll // have already been constructed when comes time for object to ask // if its to recover itself. See ARCWriterProcessor for example. onFailMessage = "Unable to test/run checkpoint recover"; this.checkpointRecover = getCheckpointRecover(); if (this.checkpointRecover == null) { this.checkpointer = new Checkpointer(this, this.checkpointsDisk); } else { setupCheckpointRecover(); } onFailMessage = "Unable to setup bdb environment."; setupBdb(); onFailMessage = "Unable to setup statistics"; setupStatTracking(); onFailMessage = "Unable to setup crawl modules"; setupCrawlModules(); } catch (Exception e) { String tmp = "On crawl: " + settingsHandler.getSettingsObject(null).getName() + " " + onFailMessage; LOGGER.log(Level.SEVERE, tmp, e); throw new InitializationException(tmp, e); } // force creation of DNS Cache now -- avoids CacheCleaner in toe-threads group // also cap size at 1 (we never wanta cached value; 0 is non-operative) Lookup.getDefaultCache(DClass.IN).setMaxEntries(1); //dns.getRecords("localhost", Type.A, DClass.IN); loopingToes = new AtomicInteger(0); setupToePool(); setThresholds(); reserveMemory = new LinkedList<char[]>(); for (int i = 1; i < RESERVE_BLOCKS; i++) { reserveMemory.add(new char[RESERVE_BLOCK_SIZE]); } }
From source file:com.wooki.domain.biz.ChapterManagerImpl.java
private synchronized ReentrantLock getOrCreateLock(Long chapterId) { assert chapterId != null; if (locks.containsKey(chapterId)) { return locks.get(chapterId); }//from w w w .ja v a 2 s. c o m ReentrantLock lock = new ReentrantLock(); locks.put(chapterId, lock); return lock; }
From source file:org.exoplatform.social.core.storage.impl.ActivityStreamStorageImpl.java
@Override public void updateCommenter(ProcessContext ctx) { final ReentrantLock lock = new ReentrantLock(); try {/* w ww . ja v a2 s. c o m*/ StreamProcessContext streamCtx = ObjectHelper.cast(StreamProcessContext.class, ctx); ExoSocialActivity activity = streamCtx.getActivity(); Identity commenter = streamCtx.getIdentity(); IdentityEntity identityEntity = identityStorage._findIdentityEntity(commenter.getProviderId(), commenter.getRemoteId()); ActivityEntity activityEntity = _findById(ActivityEntity.class, activity.getId()); // lock.lock(); QueryResult<ActivityRef> got = getActivityRefs(identityEntity, activityEntity); ActivityRef activityRef = null; while (got.hasNext()) { activityRef = got.next(); activityRef.setName("" + activity.getUpdated().getTime()); activityRef.setLastUpdated(activity.getUpdated().getTime()); } long oldUpdated = streamCtx.getOldLastUpdated(); //activity's poster != comment's poster //don't have on My Activity stream boolean has = hasActivityRefs(identityEntity, activityEntity, ActivityRefType.MY_ACTIVITIES, oldUpdated); if (has == false) { manageRefList(new UpdateContext(commenter, null), activityEntity, ActivityRefType.MY_ACTIVITIES); } //post comment also put the activity on feed if have not any has = hasActivityRefs(identityEntity, activityEntity, ActivityRefType.FEED, oldUpdated); if (has == false) { manageRefList(new UpdateContext(commenter, null), activityEntity, ActivityRefType.FEED); } //create activityref for owner's activity createRefForPoster(activityEntity, oldUpdated); } catch (NodeNotFoundException ex) { LOG.warn("Probably was updated activity reference by another session"); LOG.debug(ex.getMessage(), ex); } catch (ChromatticException ex) { Throwable throwable = ex.getCause(); if (throwable instanceof ItemExistsException || throwable instanceof InvalidItemStateException || throwable instanceof PathNotFoundException) { LOG.warn("Probably was updated activity reference by another session"); LOG.debug(ex.getMessage(), ex); } else { LOG.warn("Probably was updated activity reference by another session", ex); LOG.debug(ex.getMessage(), ex); } } finally { lock.unlock(); } }
From source file:com.epam.jdi.uitests.web.selenium.driver.SeleniumDriverFactory.java
public WebDriver getDriver(String driverName) { if (!drivers.keys().contains(driverName)) if (drivers.isEmpty()) registerDriver("DEFAULT DRIVER", getDefaultDriver()); else//w w w . j av a 2s . co m throw exception("Can't find driver with name '%s'", driverName); try { Lock lock = new ReentrantLock(); lock.lock(); if (runDrivers.get() == null || !runDrivers.get().keys().contains(driverName)) { MapArray<String, WebDriver> rDrivers = runDrivers.get(); if (rDrivers == null) rDrivers = new MapArray<>(); WebDriver resultDriver = webDriverSettings.apply(drivers.get(driverName).get()); if (resultDriver == null) throw exception("Can't get WebDriver '%s'. This Driver name not registered", driverName); rDrivers.add(driverName, resultDriver); runDrivers.set(rDrivers); } WebDriver result = runDrivers.get().get(driverName); if (result.toString().contains("(null)")) { result = webDriverSettings.apply(drivers.get(driverName).get()); runDrivers.get().update(driverName, result); } lock.unlock(); return result; } catch (Exception ex) { throw exception("Can't get driver; Thread: " + currentThread().getId() + LINE_BREAK + format("Drivers: %s; Run: %s", drivers, runDrivers) + "Exception: " + ex.getMessage()); } }
From source file:com.opentech.camel.task.TaskDomainRuntime.java
/** * //from w ww.ja v a2 s . c o m */ private void initializeDispatcher() { threadAvailableLock = new ReentrantLock(); threadAvailableCondition = threadAvailableLock.newCondition(); dispatcherThread = new Thread(new Runnable() { @Override public void run() { WrapedTask wt = null; ResourceHolder holder = null; logger.info(String.format("%s's runtime's dispacher started", taskDomain.getName())); while (!Thread.currentThread().isInterrupted()) { try { wt = getResource().getQueue().take(); // XXX wt.getResourceHolder().release(); while (null == (holder = takeThread())) { try { threadAvailableLock.lock(); threadAvailableCondition.await(1000, TimeUnit.MILLISECONDS); } finally { threadAvailableLock.unlock(); } } logger.debug(String.format("%s acquired one resource:%s", Thread.currentThread().getName(), holder)); logger.debug(String.format("%s try to execute one task", Thread.currentThread().getName())); wt.setResourceHolder(holder); _execute(wt); } catch (InterruptedException e) { logger.error(String.format("%s interrupted", Thread.currentThread().getName()), e); } catch (Throwable t) { logger.error("Disptach one task failed", t); } finally { // XXX } } logger.info(String.format("%s's runtime's dispacher stoped", taskDomain.getName())); } }, String.format("Task-Domain-Runtime-%s-Dispatcher-Thread", taskDomain.getName())); dispatcherThread.start(); }
From source file:org.wso2.andes.server.subscription.SubscriptionImpl.java
public SubscriptionImpl(AMQChannel channel, AMQProtocolSession protocolSession, AMQShortString consumerTag, FieldTable arguments, boolean noLocal, FlowCreditManager creditManager, ClientDeliveryMethod deliveryMethod, RecordDeliveryMethod recordMethod) throws AMQException { _channel = channel;//from w w w. ja v a 2 s . c o m _consumerTag = consumerTag; _creditManager = creditManager; creditManager.addStateListener(this); _noLocal = noLocal; _filters = FilterManagerFactory.createManager(arguments); _deliveryMethod = deliveryMethod; _recordMethod = recordMethod; _stateChangeLock = new ReentrantLock(); if (arguments != null) { Object autoClose = arguments.get(AMQPFilterTypes.AUTO_CLOSE.getValue()); if (autoClose != null) { _autoClose = (Boolean) autoClose; } else { _autoClose = false; } } else { _autoClose = false; } }