use of java.util.concurrent.Future in project atlas by alibaba.
the class Main method processAllFiles.
/**
* Constructs the output {@link DexFile}, fill it in with all the
* specified classes, and populate the resources map if required.
*
* @return whether processing was successful
*/
private boolean processAllFiles() {
createDexFile();
if (args.jarOutput) {
outputResources = new TreeMap<String, byte[]>();
}
anyFilesProcessed = false;
String[] fileNames = args.fileNames;
if (args.numThreads > 1) {
threadPool = Executors.newFixedThreadPool(args.numThreads);
parallelProcessorFutures = new ArrayList<Future<Void>>();
}
try {
if (args.mainDexListFile != null) {
// with --main-dex-list
FileNameFilter mainPassFilter = args.strictNameCheck ? new MainDexListFilter() : new BestEffortMainDexListFilter();
// forced in main dex
for (int i = 0; i < fileNames.length; i++) {
processOne(fileNames[i], mainPassFilter);
}
if (dexOutputArrays.size() > 0) {
throw new DexException("Too many classes in " + Arguments.MAIN_DEX_LIST_OPTION + ", main dex capacity exceeded");
}
if (args.minimalMainDex) {
// start second pass directly in a secondary dex file.
createDexFile();
}
// remaining files
for (int i = 0; i < fileNames.length; i++) {
processOne(fileNames[i], new NotFilter(mainPassFilter));
}
} else {
// without --main-dex-list
for (int i = 0; i < fileNames.length; i++) {
processOne(fileNames[i], ClassPathOpener.acceptAll);
}
}
} catch (StopProcessing ex) {
/*
* Ignore it and just let the error reporting do
* their things.
*/
}
if (args.numThreads > 1) {
try {
threadPool.shutdown();
if (!threadPool.awaitTermination(600L, TimeUnit.SECONDS)) {
throw new RuntimeException("Timed out waiting for threads.");
}
} catch (InterruptedException ex) {
threadPool.shutdownNow();
throw new RuntimeException("A thread has been interrupted.");
}
try {
for (Future<?> future : parallelProcessorFutures) {
future.get();
}
} catch (ExecutionException e) {
Throwable cause = e.getCause();
// should remain
if (cause instanceof Error) {
throw (Error) e.getCause();
} else {
throw new AssertionError(e.getCause());
}
} catch (InterruptedException e) {
// any InterruptedException
throw new AssertionError(e);
}
}
int errorNum = errors.get();
if (errorNum != 0) {
dxConsole.err.println(errorNum + " error" + ((errorNum == 1) ? "" : "s") + "; aborting");
return false;
}
if (args.incremental && !anyFilesProcessed) {
return true;
}
if (!(anyFilesProcessed || args.emptyOk)) {
dxConsole.err.println("no classfiles specified");
return false;
}
if (args.optimize && args.statistics) {
args.cfOptions.codeStatistics.dumpStatistics(dxConsole.out);
}
return true;
}
use of java.util.concurrent.Future in project javaee7-samples by javaee-samples.
the class TestMultipleInterfaceServlet method processRequest.
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<html>");
out.println("<head>");
out.println("<title>Creating contextual proxy (with multiple interfaces)</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Creating contextual proxy (with multiple interfaces)</h1>");
Object proxy = service.createContextualProxy(new MyRunnableWork(), Runnable.class, MyWork.class);
out.println("Calling MyWork interface<br>");
((MyWork) proxy).myWork();
out.println("Creating Java SE style ExecutorService<br>");
ExecutorService executor = Executors.newFixedThreadPool(10, factory);
out.println("Submitting the task<br>");
Future f = executor.submit((Runnable) proxy);
out.println("done<br><br>");
out.println("Check server.log for output from the task.");
out.println("</body>");
out.println("</html>");
}
}
use of java.util.concurrent.Future in project hibernate-orm by hibernate.
the class ConcurrentWriteTest method testManyUsers.
// Ignoring the test as it's more of a stress-test: this should be enabled manually
@Ignore
@Test
public void testManyUsers() throws Throwable {
try {
// setup - create users
for (int i = 0; i < USER_COUNT; i++) {
Customer customer = createCustomer(0);
getCustomerIDs().add(customer.getId());
}
assertEquals("failed to create enough Customers", USER_COUNT, getCustomerIDs().size());
final ExecutorService executor = Executors.newFixedThreadPool(USER_COUNT);
CyclicBarrier barrier = new CyclicBarrier(USER_COUNT + 1);
List<Future<Void>> futures = new ArrayList<Future<Void>>(USER_COUNT);
for (Integer customerId : getCustomerIDs()) {
Future<Void> future = executor.submit(new UserRunner(customerId, barrier));
futures.add(future);
// rampup
Thread.sleep(LAUNCH_INTERVAL_MILLIS);
}
// wait for all threads to finish
barrier.await(2, TimeUnit.MINUTES);
log.info("All threads finished, let's shutdown the executor and check whether any exceptions were reported");
for (Future<Void> future : futures) {
future.get();
}
executor.shutdown();
log.info("All future gets checked");
} catch (Throwable t) {
log.error("Error running test", t);
throw t;
}
}
use of java.util.concurrent.Future in project hibernate-orm by hibernate.
the class VersionedTest method testCollectionUpdate.
@Test
public void testCollectionUpdate() throws Exception {
// the first insert puts VersionedEntry(null, null, timestamp), so we have to wait a while to cache the entry
TIME_SERVICE.advance(1);
withTxSession(s -> {
Item item = s.load(Item.class, itemId);
OtherItem otherItem = new OtherItem();
otherItem.setName("Other 1");
s.persist(otherItem);
item.addOtherItem(otherItem);
});
withTxSession(s -> {
Item item = s.load(Item.class, itemId);
Set<OtherItem> otherItems = item.getOtherItems();
assertFalse(otherItems.isEmpty());
otherItems.remove(otherItems.iterator().next());
});
AdvancedCache collectionCache = ((BaseTransactionalDataRegion) sessionFactory().getSecondLevelCacheRegion(Item.class.getName() + ".otherItems")).getCache();
CountDownLatch putFromLoadLatch = new CountDownLatch(1);
AtomicBoolean committing = new AtomicBoolean(false);
CollectionUpdateTestInterceptor collectionUpdateTestInterceptor = new CollectionUpdateTestInterceptor(putFromLoadLatch);
AnotherCollectionUpdateTestInterceptor anotherInterceptor = new AnotherCollectionUpdateTestInterceptor(putFromLoadLatch, committing);
collectionCache.addInterceptor(collectionUpdateTestInterceptor, collectionCache.getInterceptorChain().size() - 1);
collectionCache.addInterceptor(anotherInterceptor, 0);
TIME_SERVICE.advance(1);
Future<Boolean> addFuture = executor.submit(() -> withTxSessionApply(s -> {
collectionUpdateTestInterceptor.updateLatch.await();
Item item = s.load(Item.class, itemId);
OtherItem otherItem = new OtherItem();
otherItem.setName("Other 2");
s.persist(otherItem);
item.addOtherItem(otherItem);
committing.set(true);
return true;
}));
Future<Boolean> readFuture = executor.submit(() -> withTxSessionApply(s -> {
Item item = s.load(Item.class, itemId);
assertTrue(item.getOtherItems().isEmpty());
return true;
}));
addFuture.get();
readFuture.get();
collectionCache.removeInterceptor(CollectionUpdateTestInterceptor.class);
collectionCache.removeInterceptor(AnotherCollectionUpdateTestInterceptor.class);
withTxSession(s -> assertFalse(s.load(Item.class, itemId).getOtherItems().isEmpty()));
}
use of java.util.concurrent.Future in project java-design-patterns by iluwatar.
the class SingletonTest method testMultipleCallsReturnTheSameObjectInDifferentThreads.
/**
* Test singleton instance in a concurrent setting
*/
@Test(timeout = 10000)
public void testMultipleCallsReturnTheSameObjectInDifferentThreads() throws Exception {
// Create 10000 tasks and inside each callable instantiate the singleton class
final List<Callable<S>> tasks = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
tasks.add(this.singletonInstanceMethod::get);
}
// Use up to 8 concurrent threads to handle the tasks
final ExecutorService executorService = Executors.newFixedThreadPool(8);
final List<Future<S>> results = executorService.invokeAll(tasks);
// wait for all of the threads to complete
final S expectedInstance = this.singletonInstanceMethod.get();
for (Future<S> res : results) {
final S instance = res.get();
assertNotNull(instance);
assertSame(expectedInstance, instance);
}
// tidy up the executor
executorService.shutdown();
}
Aggregations