List of usage examples for java.util.concurrent Semaphore acquire
public void acquire() throws InterruptedException
From source file:com.yahala.ui.GroupCreateFinalActivity.java
@SuppressWarnings("unchecked") @Override/*from w w w. jav a2 s . co m*/ public boolean onFragmentCreate() { NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces); NotificationCenter.getInstance().addObserver(this, MessagesController.chatDidCreated); NotificationCenter.getInstance().addObserver(this, MessagesController.chatDidFailCreate); avatarUpdater.parentFragment = this; avatarUpdater.delegate = this; selectedContacts = getArguments().getStringArrayList("result"); final ArrayList<String> usersToLoad = new ArrayList<String>(); for (String jid : selectedContacts) { TLRPC.User user = ContactsController.getInstance().friendsDict.get(jid); if (user == null) { usersToLoad.add(jid); } } if (!usersToLoad.isEmpty()) { final Semaphore semaphore = new Semaphore(0); final ArrayList<TLRPC.User> users = new ArrayList<TLRPC.User>(); final boolean[] error = new boolean[1]; MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { @Override public void run() { users.addAll(MessagesStorage.getInstance().getUsers(usersToLoad, error)); semaphore.release(); } }); try { semaphore.acquire(); } catch (Exception e) { FileLog.e("tmessages", e); } //if (error[0]) { // return false; // } if (!users.isEmpty()) { for (TLRPC.User user : users) { ContactsController.getInstance().friendsDict.putIfAbsent(user.jid, user); } } else { return false; } } super.onFragmentCreate(); return true; }
From source file:org.apache.asterix.experiment.client.SocketTweetGenerator.java
public void start() throws Exception { final Semaphore sem = new Semaphore((receiverAddresses.size() - 1) * -1); int i = 0;/*from www.jav a 2 s. co m*/ for (Pair<String, Integer> address : receiverAddresses) { threadPool.submit(new DataGenerator(mode, sem, address.getLeft(), address.getRight(), i + partitionRangeStart, dataGenDuration, queryGenDuration, nDataIntervals, startDataInterval, orchHost, orchPort, openStreetMapFilePath, locationSampleInterval, recordCountPerBatchDuringIngestionOnly, recordCountPerBatchDuringQuery, dataGenSleepTimeDuringIngestionOnly, dataGenSleepTimeDuringQuery)); ++i; } sem.acquire(); }
From source file:org.telegram.ui.ChannelEditActivity.java
@SuppressWarnings("unchecked") @Override/*from w ww . j a va2 s .c o m*/ public boolean onFragmentCreate() { currentChat = MessagesController.getInstance().getChat(chatId); if (currentChat == null) { final Semaphore semaphore = new Semaphore(0); MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { @Override public void run() { currentChat = MessagesStorage.getInstance().getChat(chatId); semaphore.release(); } }); try { semaphore.acquire(); } catch (Exception e) { FileLog.e("tmessages", e); } if (currentChat != null) { MessagesController.getInstance().putChat(currentChat, true); } else { return false; } if (info == null) { MessagesStorage.getInstance().loadChatInfo(chatId, semaphore, false, false); try { semaphore.acquire(); } catch (Exception e) { FileLog.e("tmessages", e); } if (info == null) { return false; } } } avatarUpdater.parentFragment = this; avatarUpdater.delegate = this; signMessages = currentChat.signatures; NotificationCenter.getInstance().addObserver(this, NotificationCenter.chatInfoDidLoaded); NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces); return super.onFragmentCreate(); }
From source file:com.thoughtworks.go.server.service.BackupServiceIntegrationTest.java
@Test public void shouldReturnBackupStartedBy() throws InterruptedException { assertThat(backupService.backupStartedBy(), is(Optional.empty())); final Semaphore waitForBackupToStart = new Semaphore(1); final Semaphore waitForAssertionToCompleteWhileBackupIsOn = new Semaphore(1); final BackupUpdateListener backupUpdateListener = new BackupUpdateListener() { private boolean backupStarted = false; @Override//from www . ja v a 2 s. com public void updateStep(BackupProgressStatus step) { if (!backupStarted) { backupStarted = true; waitForBackupToStart.release(); try { waitForAssertionToCompleteWhileBackupIsOn.acquire(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } @Override public void error(String message) { } @Override public void completed() { } }; waitForAssertionToCompleteWhileBackupIsOn.acquire(); waitForBackupToStart.acquire(); Thread backupThd = new Thread(() -> backupService.startBackup(admin, backupUpdateListener)); backupThd.start(); waitForBackupToStart.acquire(); String backupStartedBy = backupService.backupStartedBy().get(); ServerBackup runningBackup = (ServerBackup) ReflectionUtil.getField(backupService, "runningBackup"); assertThat(runningBackup.getUsername(), is(backupStartedBy)); waitForAssertionToCompleteWhileBackupIsOn.release(); backupThd.join(); }
From source file:com.thoughtworks.go.server.service.BackupServiceIntegrationTest.java
@Test public void shouldReturnBackupRunningSinceValue_inISO8601_format() throws InterruptedException { assertThat(backupService.backupRunningSinceISO8601(), is(Optional.empty())); final Semaphore waitForBackupToStart = new Semaphore(1); final Semaphore waitForAssertionToCompleteWhileBackupIsOn = new Semaphore(1); final BackupUpdateListener backupUpdateListener = new BackupUpdateListener() { private boolean backupStarted = false; @Override/*from ww w . ja v a2 s. co m*/ public void updateStep(BackupProgressStatus step) { if (!backupStarted) { backupStarted = true; waitForBackupToStart.release(); try { waitForAssertionToCompleteWhileBackupIsOn.acquire(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } @Override public void error(String message) { } @Override public void completed() { } }; waitForAssertionToCompleteWhileBackupIsOn.acquire(); waitForBackupToStart.acquire(); Thread backupThd = new Thread(() -> backupService.startBackup(admin, backupUpdateListener)); backupThd.start(); waitForBackupToStart.acquire(); String backupStartedTimeString = backupService.backupRunningSinceISO8601().get(); DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTime(); DateTime backupTime = dateTimeFormatter.parseDateTime(backupStartedTimeString); ServerBackup runningBackup = (ServerBackup) ReflectionUtil.getField(backupService, "runningBackup"); assertThat(new DateTime(runningBackup.getTime()), is(backupTime)); waitForAssertionToCompleteWhileBackupIsOn.release(); backupThd.join(); }
From source file:org.apache.flume.client.avro.TestReliableSpoolingFileEventReader.java
private void readEventsForFilesInDir(File dir, ReliableEventReader reader, Collection<String> actual, Semaphore semaphore1, Semaphore semaphore2) throws IOException { List<Event> events; boolean executed = false; for (int i = 0; i < listFiles(dir).size(); i++) { events = reader.readEvents(10);/*from ww w.ja v a 2s .c o m*/ for (Event e : events) { actual.add(new String(e.getBody())); } reader.commit(); try { if (!executed) { executed = true; if (semaphore1 != null) { semaphore1.release(); } if (semaphore2 != null) { semaphore2.acquire(); } } } catch (Exception ex) { throw new IOException(ex); } } }
From source file:org.springframework.batch.core.jsr.launch.JsrJobOperator.java
/** * Creates a child {@link ApplicationContext} for the job being requested based upon * the /META-INF/batch.xml (if exists) and the /META-INF/batch-jobs/<jobName>.xml * configuration and launches the job. Per JSR-352, calls to this method will always * create a new {@link JobInstance} (and related {@link JobExecution}). * * @param jobName the name of the job XML file without the .xml that is located within the * /META-INF/batch-jobs directory.// ww w .j ava2s . com * @param params any job parameters to be used during the execution of this job. */ @Override public long start(String jobName, Properties params) throws JobStartException, JobSecurityException { final JsrXmlApplicationContext batchContext = new JsrXmlApplicationContext(params); batchContext.setValidating(false); Resource batchXml = new ClassPathResource("/META-INF/batch.xml"); String jobConfigurationLocation = "/META-INF/batch-jobs/" + jobName + ".xml"; Resource jobXml = new ClassPathResource(jobConfigurationLocation); if (batchXml.exists()) { batchContext.load(batchXml); } if (jobXml.exists()) { batchContext.load(jobXml); } AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder .genericBeanDefinition("org.springframework.batch.core.jsr.JsrJobContextFactoryBean") .getBeanDefinition(); beanDefinition.setScope(BeanDefinition.SCOPE_SINGLETON); batchContext.registerBeanDefinition(JSR_JOB_CONTEXT_BEAN_NAME, beanDefinition); if (baseContext != null) { batchContext.setParent(baseContext); } else { batchContext.getBeanFactory().registerSingleton("jobExplorer", jobExplorer); batchContext.getBeanFactory().registerSingleton("jobRepository", jobRepository); batchContext.getBeanFactory().registerSingleton("jobParametersConverter", jobParametersConverter); batchContext.getBeanFactory().registerSingleton("transactionManager", transactionManager); } try { batchContext.refresh(); } catch (BeanCreationException e) { throw new JobStartException(e); } Assert.notNull(jobName, "The job name must not be null."); final org.springframework.batch.core.JobExecution jobExecution; try { JobParameters jobParameters = jobParametersConverter.getJobParameters(params); String[] jobNames = batchContext.getBeanNamesForType(Job.class); if (jobNames == null || jobNames.length <= 0) { throw new BatchRuntimeException("No Job defined in current context"); } org.springframework.batch.core.JobInstance jobInstance = jobRepository.createJobInstance(jobNames[0], jobParameters); jobExecution = jobRepository.createJobExecution(jobInstance, jobParameters, jobConfigurationLocation); } catch (Exception e) { throw new JobStartException(e); } try { final Semaphore semaphore = new Semaphore(1); final List<Exception> exceptionHolder = Collections.synchronizedList(new ArrayList<Exception>()); semaphore.acquire(); taskExecutor.execute(new Runnable() { @Override public void run() { JsrJobContextFactoryBean factoryBean = null; try { factoryBean = (JsrJobContextFactoryBean) batchContext .getBean("&" + JSR_JOB_CONTEXT_BEAN_NAME); factoryBean.setJobExecution(jobExecution); final Job job = batchContext.getBean(Job.class); semaphore.release(); // Initialization of the JobExecution for job level dependencies jobRegistry.register(job, jobExecution); job.execute(jobExecution); jobRegistry.remove(jobExecution); } catch (Exception e) { exceptionHolder.add(e); } finally { if (factoryBean != null) { factoryBean.close(); } batchContext.close(); if (semaphore.availablePermits() == 0) { semaphore.release(); } } } }); semaphore.acquire(); if (exceptionHolder.size() > 0) { semaphore.release(); throw new JobStartException(exceptionHolder.get(0)); } } catch (Exception e) { if (jobRegistry.exists(jobExecution.getId())) { jobRegistry.remove(jobExecution); } jobExecution.upgradeStatus(BatchStatus.FAILED); if (jobExecution.getExitStatus().equals(ExitStatus.UNKNOWN)) { jobExecution.setExitStatus(ExitStatus.FAILED.addExitDescription(e)); } jobRepository.update(jobExecution); if (batchContext.isActive()) { batchContext.close(); } throw new JobStartException(e); } return jobExecution.getId(); }
From source file:org.telegram.ui.ChannelEditTypeActivity.java
@SuppressWarnings("unchecked") @Override// w ww . j av a2 s. co m public boolean onFragmentCreate() { currentChat = MessagesController.getInstance().getChat(chatId); if (currentChat == null) { final Semaphore semaphore = new Semaphore(0); MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { @Override public void run() { currentChat = MessagesStorage.getInstance().getChat(chatId); semaphore.release(); } }); try { semaphore.acquire(); } catch (Exception e) { FileLog.e("tmessages", e); } if (currentChat != null) { MessagesController.getInstance().putChat(currentChat, true); } else { return false; } } isPrivate = currentChat.username == null || currentChat.username.length() == 0; if (isPrivate) { TLRPC.TL_channels_checkUsername req = new TLRPC.TL_channels_checkUsername(); req.username = "1"; req.channel = new TLRPC.TL_inputChannelEmpty(); ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, final TLRPC.TL_error error) { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { canCreatePublic = error == null || !error.text.equals("CHANNELS_ADMIN_PUBLIC_TOO_MUCH"); if (!canCreatePublic) { loadAdminedChannels(); } } }); } }); } NotificationCenter.getInstance().addObserver(this, NotificationCenter.chatInfoDidLoaded); return super.onFragmentCreate(); }
From source file:org.springframework.batch.core.jsr.launch.JsrJobOperator.java
/** * Creates a child {@link ApplicationContext} for the job being requested based upon * the /META-INF/batch.xml (if exists) and the /META-INF/batch-jobs/<jobName>.xml * configuration and restart the job.//from www .ja v a2 s . c o m * * @param executionId the database id of the job execution to be restarted. * @param params any job parameters to be used during the execution of this job. * @throws JobExecutionAlreadyCompleteException thrown if the requested job execution has * a status of COMPLETE * @throws NoSuchJobExecutionException throw if the requested job execution does not exist * in the repository * @throws JobExecutionNotMostRecentException thrown if the requested job execution is not * the most recent attempt for the job instance it's related to. * @throws JobRestartException thrown for any general errors during the job restart process */ @Override public long restart(long executionId, Properties params) throws JobExecutionAlreadyCompleteException, NoSuchJobExecutionException, JobExecutionNotMostRecentException, JobRestartException, JobSecurityException { org.springframework.batch.core.JobExecution previousJobExecution = jobExplorer.getJobExecution(executionId); if (previousJobExecution == null) { throw new NoSuchJobExecutionException("No JobExecution found for id: [" + executionId + "]"); } else if (previousJobExecution.getStatus().equals(BatchStatus.COMPLETED)) { throw new JobExecutionAlreadyCompleteException("The requested job has already completed"); } List<org.springframework.batch.core.JobExecution> previousExecutions = jobExplorer .getJobExecutions(previousJobExecution.getJobInstance()); for (org.springframework.batch.core.JobExecution jobExecution : previousExecutions) { if (jobExecution.getCreateTime().compareTo(previousJobExecution.getCreateTime()) > 0) { throw new JobExecutionNotMostRecentException( "The requested JobExecution to restart was not the most recently run"); } if (jobExecution.getStatus().equals(BatchStatus.ABANDONED)) { throw new JobRestartException("JobExecution ID: " + jobExecution.getId() + " is abandoned and attempted to be restarted."); } } final String jobName = previousJobExecution.getJobInstance().getJobName(); Properties jobRestartProperties = getJobRestartProperties(params, previousJobExecution); final JsrXmlApplicationContext batchContext = new JsrXmlApplicationContext(jobRestartProperties); batchContext.setValidating(false); Resource batchXml = new ClassPathResource("/META-INF/batch.xml"); Resource jobXml = new ClassPathResource(previousJobExecution.getJobConfigurationName()); if (batchXml.exists()) { batchContext.load(batchXml); } if (jobXml.exists()) { batchContext.load(jobXml); } AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder .genericBeanDefinition("org.springframework.batch.core.jsr.JsrJobContextFactoryBean") .getBeanDefinition(); beanDefinition.setScope(BeanDefinition.SCOPE_SINGLETON); batchContext.registerBeanDefinition(JSR_JOB_CONTEXT_BEAN_NAME, beanDefinition); batchContext.setParent(baseContext); try { batchContext.refresh(); } catch (BeanCreationException e) { throw new JobRestartException(e); } final org.springframework.batch.core.JobExecution jobExecution; try { JobParameters jobParameters = jobParametersConverter.getJobParameters(jobRestartProperties); jobExecution = jobRepository.createJobExecution(previousJobExecution.getJobInstance(), jobParameters, previousJobExecution.getJobConfigurationName()); } catch (Exception e) { throw new JobRestartException(e); } try { final Semaphore semaphore = new Semaphore(1); final List<Exception> exceptionHolder = Collections.synchronizedList(new ArrayList<Exception>()); semaphore.acquire(); taskExecutor.execute(new Runnable() { @Override public void run() { JsrJobContextFactoryBean factoryBean = null; try { factoryBean = (JsrJobContextFactoryBean) batchContext .getBean("&" + JSR_JOB_CONTEXT_BEAN_NAME); factoryBean.setJobExecution(jobExecution); final Job job = batchContext.getBean(Job.class); if (!job.isRestartable()) { throw new JobRestartException("Job " + jobName + " is not restartable"); } semaphore.release(); // Initialization of the JobExecution for job level dependencies jobRegistry.register(job, jobExecution); job.execute(jobExecution); jobRegistry.remove(jobExecution); } catch (Exception e) { exceptionHolder.add(e); } finally { if (factoryBean != null) { factoryBean.close(); } batchContext.close(); if (semaphore.availablePermits() == 0) { semaphore.release(); } } } }); semaphore.acquire(); if (exceptionHolder.size() > 0) { semaphore.release(); throw new JobRestartException(exceptionHolder.get(0)); } } catch (Exception e) { jobExecution.upgradeStatus(BatchStatus.FAILED); if (jobExecution.getExitStatus().equals(ExitStatus.UNKNOWN)) { jobExecution.setExitStatus(ExitStatus.FAILED.addExitDescription(e)); } jobRepository.update(jobExecution); if (batchContext.isActive()) { batchContext.close(); } throw new JobRestartException(e); } return jobExecution.getId(); }
From source file:com.alibaba.napoli.client.benchmark.NapoliNormalQueueTest.java
@Test public void sendMessageWithSenderStoreEnableTest() throws Exception { log.info("start to execute sendMessageWithSenderStoreEnableTest"); long beginQueueSize = JmxUtil.getQueueSize(sendConnector.getAddress(), queueName); qSender = new DefaultAsyncSender(); qSender.setConnector(sendConnector); qSender.setName(queueName);// w ww . j ava2s .c o m qSender.setStoreEnable(true); qSender.setReprocessInterval(10000 * 1000 * 1000); qSender.init(); int tc = 10; log.info("yanny requestcount = " + System.getProperty("requestCount") + ", begin queue size is " + beginQueueSize); final int tp = Integer.parseInt(System.getProperty("requestCount", "20")); final Semaphore semaphore = new Semaphore(tc); final AtomicInteger sumCount = new AtomicInteger(); final AtomicInteger requestCount = new AtomicInteger(); long startTime = System.currentTimeMillis(); log.info("Yanny start send request " + startTime); for (int i = 0; i < tc; i++) { Thread t = new Thread("thread--" + i) { public void run() { try { //?tringap??Serializable semaphore.acquire(); Person person = new Person(); person.setLoginName("superman"); person.setEmail("sm@1.com"); person.setPenName("pname"); person.setStatus(PersonStatus.ENABLED); for (int j = 0; j < tp; j++) { // log.info("hello"); int id = requestCount.incrementAndGet(); person.setPersonId("" + id); //?? ??true???alse boolean result = qSender.send(person); if (!result) { log.info("----------------send to queue " + "result is false. personid=" + j); } else { sumCount.incrementAndGet(); } } } catch (Throwable t) { t.printStackTrace(); } finally { semaphore.release(); } } }; t.start(); } while (semaphore.availablePermits() != tc) { Thread.sleep(100); } int totalRequest = tc * tp; long endTime = System.currentTimeMillis(); log.info("yanny: send " + totalRequest + " message, take " + (endTime - startTime) + " milseconds"); JmxUtil.waitTillQueueSizeAsTarget(sendConnector.getAddress(), queueName, beginQueueSize); endTime = System.currentTimeMillis(); String errorMessage = ""; long qBdbCount = NapoliTestUtil.getStoreSize(sendConnector.getSenderKVStore(qSender.getName())); log.info("yanny totalRequest " + totalRequest + " send queue success " + sumCount + " local store count:" + qBdbCount + " queue received " + qWorker.getAccessNum() + " take " + (endTime - startTime) + " milseconds"); log.info(initConsumeMessage); log.info("NapoliNormalQueueTest's success=" + qWorker.getAccessNum() + " bdb's size=" + qBdbCount); //with store enabled, all send should succeed. if (qSender.getStoreEnable()) { if (sumCount.get() != totalRequest) { errorMessage += ";with store enabled, all send should return success, but not equal now. send succeed " + sumCount.get() + "; total request:" + totalRequest; } } else { if (sumCount.get() < totalRequest * 0.95) { errorMessage += ";with store disabled, expected more than 95% message send succeed, total request:" + totalRequest + "; send succeed " + sumCount.get(); } } if (sumCount.get() < qWorker.getAccessNum()) { errorMessage += ";queue should not have success messages more than send succeed" + sumCount.get() + " (success " + qWorker.getAccessNum() + ")"; } if ((sumCount.get() - qBdbCount) > qWorker.getAccessNum()) { errorMessage += ";queue received message (" + qWorker.getAccessNum() + ") less than send succeed - local stored message, message lost " + (sumCount.get() - qBdbCount); } int allowedDiff = (int) Math.round(sumCount.get() * 0.001); if (((qWorker.getAccessNum() + qBdbCount) - sumCount.get()) > allowedDiff) { errorMessage += "queue received message should not have more than send succeed + " + allowedDiff + " than allowed (0.1%), gap " + ((qWorker.getAccessNum() + qBdbCount) - sumCount.get()); } assertTrue(errorMessage, errorMessage.equals("")); verify(napoliSenderStat, atMost(qWorker.getAccessNum())).sendSuccess(anyLong(), anyLong()); verify(napoliSenderStat, atLeast((int) (sumCount.get() - qBdbCount))).sendSuccess(anyLong(), anyLong()); verify(napoliSenderStat, times((int) qBdbCount)).sendFailure(anyLong(), anyLong()); verify(napoliReceiverStat, times((int) qWorker.getAccessNum())).receiveSuccess(anyLong(), anyLong()); }