List of usage examples for java.util.concurrent.atomic AtomicInteger intValue
public int intValue()
From source file:com.ciphertool.sentencebuilder.etl.importers.FrequencyListImporterImplTest.java
@SuppressWarnings("unchecked") @Test/* www .j a v a2s . co m*/ public void testImportWord() { FrequencyListImporterImpl frequencyListImporterImpl = new FrequencyListImporterImpl(); Field rowUpdateCountField = ReflectionUtils.findField(FrequencyListImporterImpl.class, "rowUpdateCount"); ReflectionUtils.makeAccessible(rowUpdateCountField); AtomicInteger rowUpdateCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowUpdateCountField, frequencyListImporterImpl); assertEquals(0, rowUpdateCountFromObject.intValue()); Field rowInsertCountField = ReflectionUtils.findField(FrequencyListImporterImpl.class, "rowInsertCount"); ReflectionUtils.makeAccessible(rowInsertCountField); AtomicInteger rowInsertCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowInsertCountField, frequencyListImporterImpl); assertEquals(0, rowInsertCountFromObject.intValue()); WordDao wordDaoMock = mock(WordDao.class); when(wordDaoMock.insertBatch(anyListOf(Word.class))).thenReturn(true); when(wordDaoMock.updateBatch(anyListOf(Word.class))).thenReturn(true); frequencyListImporterImpl.setWordDao(wordDaoMock); frequencyListImporterImpl.setPersistenceBatchSize(2); List<Word> insertBatch = new ArrayList<Word>(); List<Word> updateBatch = new ArrayList<Word>(); Word word1 = new Word(new WordId("george", PartOfSpeechType.NOUN), 100); Word word2 = new Word(new WordId("belden", PartOfSpeechType.NOUN), 200); Word word3 = new Word(new WordId("is", PartOfSpeechType.VERB_PARTICIPLE), 300); Word word4 = new Word(new WordId("awesome", PartOfSpeechType.ADJECTIVE), 400); Word wordFromDatabase1 = new Word(new WordId("george", PartOfSpeechType.NOUN)); Word wordFromDatabase2 = new Word(new WordId("belden", PartOfSpeechType.NOUN)); when(wordDaoMock.findByWordString(anyString())).thenReturn(Arrays.asList(wordFromDatabase1), Arrays.asList(wordFromDatabase2), null, null); frequencyListImporterImpl.importWord(word1, insertBatch, updateBatch); verify(wordDaoMock, never()).insertBatch(anyListOf(Word.class)); verify(wordDaoMock, never()).updateBatch(anyListOf(Word.class)); assertEquals(1, updateBatch.size()); assertTrue(insertBatch.isEmpty()); frequencyListImporterImpl.importWord(word2, insertBatch, updateBatch); verify(wordDaoMock, never()).insertBatch(anyListOf(Word.class)); verify(wordDaoMock, times(1)).updateBatch(anyListOf(Word.class)); assertTrue(updateBatch.isEmpty()); assertTrue(insertBatch.isEmpty()); frequencyListImporterImpl.importWord(word3, insertBatch, updateBatch); verify(wordDaoMock, never()).insertBatch(anyListOf(Word.class)); verify(wordDaoMock, times(1)).updateBatch(anyListOf(Word.class)); assertTrue(updateBatch.isEmpty()); assertEquals(1, insertBatch.size()); frequencyListImporterImpl.importWord(word4, insertBatch, updateBatch); verify(wordDaoMock, times(1)).insertBatch(anyListOf(Word.class)); verify(wordDaoMock, times(1)).updateBatch(anyListOf(Word.class)); assertTrue(updateBatch.isEmpty()); assertTrue(insertBatch.isEmpty()); rowUpdateCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowUpdateCountField, frequencyListImporterImpl); rowInsertCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowInsertCountField, frequencyListImporterImpl); assertEquals(100, wordFromDatabase1.getFrequencyWeight()); assertEquals(200, wordFromDatabase2.getFrequencyWeight()); assertEquals(2, rowUpdateCountFromObject.intValue()); assertEquals(2, rowInsertCountFromObject.intValue()); verify(wordDaoMock, times(4)).findByWordString(anyString()); }
From source file:com.ciphertool.sentencebuilder.etl.importers.FrequencyListImporterImplTest.java
@SuppressWarnings("unchecked") @Test// ww w .ja va 2 s. com public void testImportWord_BatchSizeNotReached() { FrequencyListImporterImpl frequencyListImporterImpl = new FrequencyListImporterImpl(); Field rowUpdateCountField = ReflectionUtils.findField(FrequencyListImporterImpl.class, "rowUpdateCount"); ReflectionUtils.makeAccessible(rowUpdateCountField); AtomicInteger rowUpdateCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowUpdateCountField, frequencyListImporterImpl); assertEquals(0, rowUpdateCountFromObject.intValue()); Field rowInsertCountField = ReflectionUtils.findField(FrequencyListImporterImpl.class, "rowInsertCount"); ReflectionUtils.makeAccessible(rowInsertCountField); AtomicInteger rowInsertCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowInsertCountField, frequencyListImporterImpl); assertEquals(0, rowInsertCountFromObject.intValue()); WordDao wordDaoMock = mock(WordDao.class); when(wordDaoMock.insertBatch(anyListOf(Word.class))).thenReturn(true); when(wordDaoMock.updateBatch(anyListOf(Word.class))).thenReturn(true); frequencyListImporterImpl.setWordDao(wordDaoMock); frequencyListImporterImpl.setPersistenceBatchSize(3); List<Word> insertBatch = new ArrayList<Word>(); List<Word> updateBatch = new ArrayList<Word>(); Word word1 = new Word(new WordId("george", PartOfSpeechType.NOUN), 100); Word word2 = new Word(new WordId("belden", PartOfSpeechType.NOUN), 200); Word word3 = new Word(new WordId("is", PartOfSpeechType.VERB_PARTICIPLE), 300); Word word4 = new Word(new WordId("awesome", PartOfSpeechType.ADJECTIVE), 400); Word wordFromDatabase1 = new Word(new WordId("george", PartOfSpeechType.NOUN)); Word wordFromDatabase2 = new Word(new WordId("belden", PartOfSpeechType.NOUN)); when(wordDaoMock.findByWordString(anyString())).thenReturn(Arrays.asList(wordFromDatabase1), Arrays.asList(wordFromDatabase2), null, null); frequencyListImporterImpl.importWord(word1, insertBatch, updateBatch); verify(wordDaoMock, never()).insertBatch(anyListOf(Word.class)); verify(wordDaoMock, never()).updateBatch(anyListOf(Word.class)); assertEquals(1, updateBatch.size()); assertTrue(insertBatch.isEmpty()); frequencyListImporterImpl.importWord(word2, insertBatch, updateBatch); verify(wordDaoMock, never()).insertBatch(anyListOf(Word.class)); verify(wordDaoMock, never()).updateBatch(anyListOf(Word.class)); assertEquals(2, updateBatch.size()); assertTrue(insertBatch.isEmpty()); frequencyListImporterImpl.importWord(word3, insertBatch, updateBatch); verify(wordDaoMock, never()).insertBatch(anyListOf(Word.class)); verify(wordDaoMock, never()).updateBatch(anyListOf(Word.class)); assertEquals(2, updateBatch.size()); assertEquals(1, insertBatch.size()); frequencyListImporterImpl.importWord(word4, insertBatch, updateBatch); verify(wordDaoMock, never()).insertBatch(anyListOf(Word.class)); verify(wordDaoMock, never()).updateBatch(anyListOf(Word.class)); assertEquals(2, updateBatch.size()); assertEquals(2, insertBatch.size()); rowUpdateCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowUpdateCountField, frequencyListImporterImpl); rowInsertCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowInsertCountField, frequencyListImporterImpl); assertEquals(100, wordFromDatabase1.getFrequencyWeight()); assertEquals(200, wordFromDatabase2.getFrequencyWeight()); assertEquals(0, rowUpdateCountFromObject.intValue()); assertEquals(0, rowInsertCountFromObject.intValue()); verify(wordDaoMock, times(4)).findByWordString(anyString()); }
From source file:com.ciphertool.sentencebuilder.etl.importers.FrequencyListImporterImplTest.java
@Test public void testBatchWordImportTask_LeftoversFromBatch() { FrequencyListImporterImpl frequencyListImporterImpl = new FrequencyListImporterImpl(); Word word1 = new Word(new WordId("george", PartOfSpeechType.NOUN), 100); Word word2 = new Word(new WordId("belden", PartOfSpeechType.NOUN), 200); Word word3 = new Word(new WordId("is", PartOfSpeechType.VERB_PARTICIPLE), 300); Word word4 = new Word(new WordId("super", PartOfSpeechType.ADJECTIVE), 400); Word word5 = new Word(new WordId("seriously", PartOfSpeechType.ADJECTIVE), 500); Word word6 = new Word(new WordId("awesome", PartOfSpeechType.ADJECTIVE), 600); List<Word> threadBatch = new ArrayList<Word>(); threadBatch.add(word1);// w w w . j av a2 s.c o m threadBatch.add(word2); threadBatch.add(word3); threadBatch.add(word4); threadBatch.add(word5); threadBatch.add(word6); FrequencyListImporterImpl.BatchWordImportTask batchWordImportTask = frequencyListImporterImpl.new BatchWordImportTask( threadBatch); Field rowUpdateCountField = ReflectionUtils.findField(FrequencyListImporterImpl.class, "rowUpdateCount"); ReflectionUtils.makeAccessible(rowUpdateCountField); AtomicInteger rowUpdateCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowUpdateCountField, frequencyListImporterImpl); assertEquals(0, rowUpdateCountFromObject.intValue()); Field rowInsertCountField = ReflectionUtils.findField(FrequencyListImporterImpl.class, "rowInsertCount"); ReflectionUtils.makeAccessible(rowInsertCountField); AtomicInteger rowInsertCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowInsertCountField, frequencyListImporterImpl); assertEquals(0, rowInsertCountFromObject.intValue()); WordDao wordDaoMock = mock(WordDao.class); when(wordDaoMock.insertBatch(anyListOf(Word.class))).thenReturn(true); int persistenceBatchSizeToSet = 2; int concurrencyBatchSizeToSet = 3; frequencyListImporterImpl.setWordDao(wordDaoMock); frequencyListImporterImpl.setPersistenceBatchSize(persistenceBatchSizeToSet); frequencyListImporterImpl.setConcurrencyBatchSize(concurrencyBatchSizeToSet); Word wordFromDatabase1 = new Word(new WordId("george", PartOfSpeechType.NOUN)); Word wordFromDatabase2 = new Word(new WordId("belden", PartOfSpeechType.NOUN)); Word wordFromDatabase3 = new Word(new WordId("is", PartOfSpeechType.ADJECTIVE)); when(wordDaoMock.insertBatch(anyListOf(Word.class))).thenReturn(true); when(wordDaoMock.updateBatch(anyListOf(Word.class))).thenReturn(true); when(wordDaoMock.findByWordString(eq("george"))).thenReturn(Arrays.asList(wordFromDatabase1)); when(wordDaoMock.findByWordString(eq("belden"))).thenReturn(Arrays.asList(wordFromDatabase2)); when(wordDaoMock.findByWordString(eq("is"))).thenReturn( Arrays.asList(wordFromDatabase3)); when(wordDaoMock.findByWordString(eq("super"))).thenReturn(null); when(wordDaoMock.findByWordString(eq("seriously"))).thenReturn(null); when(wordDaoMock.findByWordString(eq("awesome"))).thenReturn(null); try { batchWordImportTask.call(); } catch (Exception e) { fail(e.getMessage()); } assertEquals(100, wordFromDatabase1.getFrequencyWeight()); assertEquals(200, wordFromDatabase2.getFrequencyWeight()); assertEquals(300, wordFromDatabase3.getFrequencyWeight()); rowUpdateCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowUpdateCountField, frequencyListImporterImpl); rowInsertCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowInsertCountField, frequencyListImporterImpl); assertEquals(3, rowUpdateCountFromObject.intValue()); assertEquals(3, rowInsertCountFromObject.intValue()); verify(wordDaoMock, times(2)).insertBatch(anyListOf(Word.class)); verify(wordDaoMock, times(2)).updateBatch(anyListOf(Word.class)); verify(wordDaoMock, times(6)).findByWordString(anyString()); }
From source file:com.ciphertool.sentencebuilder.etl.importers.FrequencyListImporterImplTest.java
@Test public void testImportFrequencyList_LeftoversFromBatch() { ThreadPoolTaskExecutor taskExecutorSpy = spy(new ThreadPoolTaskExecutor()); taskExecutorSpy.setCorePoolSize(4);/*from w w w.j ava 2 s. com*/ taskExecutorSpy.setMaxPoolSize(4); taskExecutorSpy.setQueueCapacity(100); taskExecutorSpy.setKeepAliveSeconds(1); taskExecutorSpy.setAllowCoreThreadTimeOut(true); taskExecutorSpy.initialize(); FrequencyListImporterImpl frequencyListImporterImpl = new FrequencyListImporterImpl(); frequencyListImporterImpl.setTaskExecutor(taskExecutorSpy); Field rowUpdateCountField = ReflectionUtils.findField(FrequencyListImporterImpl.class, "rowUpdateCount"); ReflectionUtils.makeAccessible(rowUpdateCountField); AtomicInteger rowUpdateCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowUpdateCountField, frequencyListImporterImpl); assertEquals(0, rowUpdateCountFromObject.intValue()); Field rowInsertCountField = ReflectionUtils.findField(FrequencyListImporterImpl.class, "rowInsertCount"); ReflectionUtils.makeAccessible(rowInsertCountField); AtomicInteger rowInsertCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowInsertCountField, frequencyListImporterImpl); assertEquals(0, rowInsertCountFromObject.intValue()); WordDao wordDaoMock = mock(WordDao.class); when(wordDaoMock.insertBatch(anyListOf(Word.class))).thenReturn(true); int persistenceBatchSizeToSet = 3; int concurrencyBatchSizeToSet = 2; frequencyListImporterImpl.setWordDao(wordDaoMock); frequencyListImporterImpl.setPersistenceBatchSize(persistenceBatchSizeToSet); frequencyListImporterImpl.setConcurrencyBatchSize(concurrencyBatchSizeToSet); Word word1 = new Word(new WordId("george", PartOfSpeechType.NOUN), 100); Word word2 = new Word(new WordId("belden", PartOfSpeechType.NOUN), 200); Word word3 = new Word(new WordId("is", PartOfSpeechType.VERB_PARTICIPLE), 300); Word word4 = new Word(new WordId("super", PartOfSpeechType.ADJECTIVE), 400); Word word5 = new Word(new WordId("awesome", PartOfSpeechType.ADJECTIVE), 500); List<Word> wordsToReturn = new ArrayList<Word>(); wordsToReturn.add(word1); wordsToReturn.add(word2); wordsToReturn.add(word3); wordsToReturn.add(word4); wordsToReturn.add(word5); FrequencyFileParser fileParserMock = mock(FrequencyFileParser.class); when(fileParserMock.parseFile()).thenReturn(wordsToReturn); frequencyListImporterImpl.setFileParser(fileParserMock); Word wordFromDatabase1 = new Word(new WordId("george", PartOfSpeechType.NOUN)); Word wordFromDatabase2 = new Word(new WordId("belden", PartOfSpeechType.NOUN)); Word wordFromDatabase3 = new Word(new WordId("is", PartOfSpeechType.ADJECTIVE)); when(wordDaoMock.insertBatch(anyListOf(Word.class))).thenReturn(true); when(wordDaoMock.updateBatch(anyListOf(Word.class))).thenReturn(true); when(wordDaoMock.findByWordString(eq("george"))).thenReturn(Arrays.asList(wordFromDatabase1)); when(wordDaoMock.findByWordString(eq("belden"))).thenReturn(Arrays.asList(wordFromDatabase2)); when(wordDaoMock.findByWordString(eq("is"))).thenReturn( Arrays.asList(wordFromDatabase3)); when(wordDaoMock.findByWordString(eq("super"))).thenReturn(null); when(wordDaoMock.findByWordString(eq("seriously"))).thenReturn(null); when(wordDaoMock.findByWordString(eq("awesome"))).thenReturn(null); frequencyListImporterImpl.importFrequencyList(); assertEquals(100, wordFromDatabase1.getFrequencyWeight()); assertEquals(200, wordFromDatabase2.getFrequencyWeight()); assertEquals(300, wordFromDatabase3.getFrequencyWeight()); rowUpdateCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowUpdateCountField, frequencyListImporterImpl); rowInsertCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowInsertCountField, frequencyListImporterImpl); assertEquals(3, rowUpdateCountFromObject.intValue()); assertEquals(2, rowInsertCountFromObject.intValue()); verify(wordDaoMock, times(2)).insertBatch(anyListOf(Word.class)); verify(wordDaoMock, times(2)).updateBatch(anyListOf(Word.class)); verify(wordDaoMock, times(5)).findByWordString(anyString()); verify(taskExecutorSpy, times(3)).execute(any(Runnable.class)); }
From source file:edu.brown.workload.Workload.java
/** * //from w w w. j a v a 2 s. com * @param txn_id * @param catalog_stmt * @param catalog_statement * @param args * @return * @throws Exception */ @Override public Object startQuery(Object xact_handle, Statement catalog_statement, Object args[], int batch_id) { QueryTrace query_handle = null; if (xact_handle instanceof TransactionTrace) { TransactionTrace xact = (TransactionTrace) xact_handle; long txn_id = xact.getTransactionId(); if (this.ignored_xact_ids.contains(txn_id)) return (null); Map<Integer, AtomicInteger> open_queries = this.xact_open_queries.get(txn_id); // HACK if (open_queries == null) { open_queries = new HashMap<Integer, AtomicInteger>(); this.xact_open_queries.put(txn_id, open_queries); } assert (open_queries != null) : "Starting a query before starting the txn?? [" + txn_id + "]"; query_handle = new QueryTrace(catalog_statement, args, batch_id); xact.addQuery(query_handle); this.query_txn_xref.put(query_handle, txn_id); // Make sure that there aren't still running queries in the previous batch if (batch_id > 0) { AtomicInteger last_batch_ctr = open_queries.get(batch_id - 1); if (last_batch_ctr != null && last_batch_ctr.intValue() != 0) { String msg = "Txn #" + txn_id + " is trying to start a new query in batch #" + batch_id + " but there are still " + last_batch_ctr.intValue() + " queries running in batch #" + (batch_id - 1); throw new IllegalStateException(msg); } } AtomicInteger batch_ctr = open_queries.get(batch_id); if (batch_ctr == null) { synchronized (open_queries) { batch_ctr = new AtomicInteger(0); open_queries.put(batch_id, batch_ctr); } // SYNCHRONIZED } batch_ctr.incrementAndGet(); if (debug.val) LOG.debug("Created '" + catalog_statement.getName() + "' query trace record for xact '" + txn_id + "'"); } else { LOG.fatal("Unable to create new query trace: Invalid transaction handle"); } return (query_handle); }
From source file:com.shopzilla.hadoop.mapreduce.MiniMRClusterContextPigTest.java
@Test public void testPig() throws Exception { final AtomicInteger inputRecordCount = new AtomicInteger(0); miniMRClusterContext.processData(new Path("/user/test/keywords_data"), new Function<String, Void>() { @Override//w ww . jav a 2 s.co m public Void apply(String line) { inputRecordCount.incrementAndGet(); return null; } }); Map<String, String> params = ImmutableMap.<String, String>builder().put("INPUT", "/user/test/keywords_data") .put("OUTPUT", "/user/test/keywords_output").build(); PigServer pigServer = miniMRClusterContext.getPigServer(); pigServer.registerScript(new ClassPathResource("some_pig_script.pig").getInputStream(), params); pigServer.setBatchOn(); pigServer.executeBatch(); final AtomicInteger outputRecordCount = new AtomicInteger(0); miniMRClusterContext.processData(new Path("/user/test/keywords_output"), new Function<String, Void>() { @Override public Void apply(String line) { outputRecordCount.incrementAndGet(); return null; } }); assertEquals(inputRecordCount.intValue(), outputRecordCount.intValue()); }
From source file:org.apache.taverna.scufl2.translator.t2flow.T2FlowParser.java
protected Set<DataLink> parseDatalinks(Datalinks origLinks) throws ReaderException { HashSet<DataLink> newLinks = new HashSet<>(); Map<ReceiverPort, AtomicInteger> mergeCounts = new HashMap<>(); for (org.apache.taverna.scufl2.xml.t2flow.jaxb.DataLink origLink : origLinks.getDatalink()) { try {/* w ww .j a v a 2 s . c o m*/ SenderPort senderPort = findSenderPort(parserState.get().getCurrentWorkflow(), origLink.getSource()); ReceiverPort receiverPort = findReceiverPort(parserState.get().getCurrentWorkflow(), origLink.getSink()); DataLink newLink = new DataLink(parserState.get().getCurrentWorkflow(), senderPort, receiverPort); AtomicInteger mergeCount = mergeCounts.get(receiverPort); if (origLink.getSink().getType().equals(MERGE)) { if (mergeCount != null && mergeCount.intValue() < 1) throw new ReaderException("Merged and non-merged links to port " + receiverPort); if (mergeCount == null) { mergeCount = new AtomicInteger(0); mergeCounts.put(receiverPort, mergeCount); } newLink.setMergePosition(mergeCount.getAndIncrement()); } else { if (mergeCount != null) throw new ReaderException("More than one link to non-merged port " + receiverPort); mergeCounts.put(receiverPort, new AtomicInteger(-1)); } // FIXME: missing from t2flow and schema //parseAnnotations(newLink, origLink.getAnnotations()); newLinks.add(newLink); } catch (ReaderException ex) { logger.log(WARNING, "Could not translate link:\n" + origLink, ex); if (isStrict()) throw ex; continue; } } return newLinks; }
From source file:org.atemsource.atem.utility.view.ViewBuilderTest.java
@Test public void testRemoveAndIncludePrimitives() { EntityType<EntityA> entityType = entityTypeRepository.getEntityType(EntityA.class); ViewBuilder viewBuilder = factory.create(entityType); viewBuilder.includePrimitives(false); viewBuilder.remove("intP"); View view = viewBuilder.create(); final Attribute intPAttribute = entityType.getAttribute("intP"); final AtomicInteger count = new AtomicInteger(); final ViewVisitor mockViewVisitor = new ViewVisitor<Object>() { @Override//from w ww . j a v a 2 s .c om public void visit(Object context, Attribute attribute) { if (attribute == intPAttribute) { Assert.fail("intP was removed"); } else if (attribute.getTargetType() instanceof PrimitiveType<?> && attribute instanceof SingleAttribute<?>) { count.incrementAndGet(); } else { Assert.fail("not a single primitive " + attribute.getCode()); } } @Override public void visit(Object context, Attribute attribute, Visitor<Object> visitor) { Assert.fail("not a primitive " + attribute.getCode()); } @Override public void visitSubView(Object context, View view, Visitor<Object> subViewVisitor) { } @Override public void visitSuperView(Object context, View view, Visitor<Object> superViewVisitor) { } }; HierachyVisitor.visit(view, mockViewVisitor, null); Assert.assertTrue(count.intValue() > 2); }
From source file:org.jspresso.hrsample.backend.JspressoUnitOfWorkTest.java
/** * Tests in TX collection element update with // optimistic locking. *///from w w w . jav a2 s .c o m @Test public void testInTXCollectionElementUpdate() { final HibernateBackendController hbc = (HibernateBackendController) getBackendController(); final AtomicInteger countDown = new AtomicInteger(10); ExecutorService es = Executors.newFixedThreadPool(countDown.get()); List<Future<Set<String>>> futures = new ArrayList<Future<Set<String>>>(); for (int t = countDown.intValue(); t > 0; t--) { futures.add(es.submit(new Callable<Set<String>>() { @Override public Set<String> call() throws Exception { final HibernateBackendController threadHbc = getApplicationContext() .getBean("applicationBackController", HibernateBackendController.class); final TransactionTemplate threadTT = threadHbc.getTransactionTemplate(); threadHbc.start(hbc.getLocale(), hbc.getClientTimeZone()); threadHbc.setApplicationSession(hbc.getApplicationSession()); BackendControllerHolder.setThreadBackendController(threadHbc); return threadTT.execute(new TransactionCallback<Set<String>>() { /** * {@inheritDoc} */ @Override public Set<String> doInTransaction(TransactionStatus status) { DetachedCriteria compCrit = DetachedCriteria.forClass(Company.class); Set<String> names = new HashSet<String>(); Company c = (Company) compCrit.getExecutableCriteria(threadHbc.getHibernateSession()) .list().iterator().next(); synchronized (countDown) { countDown.decrementAndGet(); // wait for all threads to arrive here so that we are sure they // have all read the same data. try { countDown.wait(); } catch (InterruptedException ex) { throw new BackendException("Test has been interrupted"); } } if (c.getName().startsWith("TX_")) { throw new BackendException("Wrong data read from DB"); } c.setName("TX_" + Long.toHexString(System.currentTimeMillis())); names.add(c.getName()); for (Department d : c.getDepartments()) { d.setName(Long.toHexString(System.currentTimeMillis())); names.add(d.getName()); } return names; } }); } })); } while (countDown.get() > 0) { try { Thread.sleep(200); } catch (InterruptedException ex) { throw new BackendException("Test has been interrupted"); } } synchronized (countDown) { countDown.notifyAll(); } int successfullTxCount = 0; Set<String> names = new HashSet<String>(); for (Future<Set<String>> f : futures) { try { names = f.get(); successfullTxCount++; } catch (Exception ex) { if (ex.getCause() instanceof OptimisticLockingFailureException) { // safely ignore since this is what we are testing. } else { throw new BackendException(ex); } } } es.shutdown(); assertTrue("Only 1 TX succeeded", successfullTxCount == 1); DetachedCriteria compCrit = DetachedCriteria.forClass(Company.class); Company c = hbc.findFirstByCriteria(compCrit, EMergeMode.MERGE_LAZY, Company.class); assertTrue("the company name is the one of the successfull TX", names.contains(c.getName())); for (Department d : c.getDepartments()) { assertTrue("the department name is the one of the successfull TX", names.contains(d.getName())); } }
From source file:com.supermy.flume.interceptor.RuleThreadSearchAndReplaceInterceptor.java
@Override public List<Event> intercept(List<Event> events) { //todo//from w w w .j a v a2 s .c o m long s = System.currentTimeMillis(); final AtomicInteger ai = new AtomicInteger(0); List<Future<Event>> results = new ArrayList<Future<Event>>(); for (final Event event : events) { Future<Event> future = executorService.submit(new Callable<Event>() { @Override public Event call() { ai.incrementAndGet(); return intercept(event); } }); results.add(future); } // List<Event> out = Lists.newArrayList(); for (Future<Event> future : results) { Event event = null; try { event = future.get(); // // out.add(event); // if (event != null) { // out.add(event); // } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } long e = System.currentTimeMillis(); logger.info("rules:{}??{}", Thread.activeCount(), ai.intValue()); logger.info("rules:???{}", ai.intValue() / (e - s) / 1000); logger.info("rules:???{}", events.size() / (e - s) / 1000); return events; // return out; }