List of usage examples for java.util.concurrent Executors callable
public static Callable<Object> callable(final PrivilegedExceptionAction<?> action)
From source file:Main.java
public static Future<Object> execute(final Runnable task) { return DEFAULT_EXECUTOR.submit(Executors.callable(task)); }
From source file:com.google.code.guice.repository.testing.junit.general.UserRepositoryTest.java
@Test public void testRepo() throws Exception { userRepository.deleteAll();//w w w. j a v a 2 s . co m userRepository.someCustomMethod(new User("one", "two", 42)); userRepository.deleteInactiveUsers(); userRepository.deleteOtherUsers(); userRepository.deleteAll(); assertEquals("Invalid repository size", 0, userRepository.count()); userRepository.save(new User("john", "smith", 42)); userRepository.save(new User("alex", "johns", 33)); userRepository.save(new User("sam", "brown", 22)); assertEquals("Invalid repository size", 3, userRepository.count()); assertNotNull("User not found", userRepository.findUserByName("john")); Page<User> users = userRepository.findAll(new PageRequest(0, 100)); assertEquals("Invalid requested page size", 3, users.getNumberOfElements()); ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.invokeAll(Arrays.asList(Executors.callable(new Runnable() { @Override public void run() { try { logger.info("Start concurrent thread"); UserRepository anotherRepo = userRepository; logger.info("count"); assertEquals("Invalid repository size", 3, anotherRepo.count()); logger.info("save"); anotherRepo.save(new User(UUID.randomUUID().toString(), UUID.randomUUID().toString(), 10)); assertEquals("Invalid repository size", 4, anotherRepo.count()); logger.info("Stored 4"); } catch (Exception e) { logger.error("Error", e); } } }))); logger.info("After"); assertEquals("Invalid repository size", 4, userRepository.count()); userRepository.deleteAll(); assertEquals("Invalid repository size", 0, userRepository.count()); userRepository.someCustomMethod(new User("john", "smith", 42)); }
From source file:de.unisb.cs.st.javalanche.mutation.runtime.testDriver.MutationTestDriver.java
protected long runWithTimeout(MutationTestRunnable r) { long[] preIds = threadMxBean.getAllThreadIds(); FutureTask<Object> future = new FutureTask<Object>(Executors.callable(r)); Thread thread = new Thread(future); thread.setDaemon(true);//from ww w . j a va 2 s . c om logger.debug("Start test: "); StopWatch stopWatch = new StopWatch(); stopWatch.start(); thread.start(); String exceptionMessage = null; Throwable capturedThrowable = null; try { future.get(timeout, TimeUnit.SECONDS); logger.debug("Second timeout"); } catch (InterruptedException e) { capturedThrowable = e; } catch (ExecutionException e) { capturedThrowable = e; } catch (TimeoutException e) { exceptionMessage = JavalancheMessages.MUTATION_TIME_LIMIT_MESSAGE + "Mutation causes test timeout"; capturedThrowable = e; } catch (Throwable t) { capturedThrowable = t; } finally { if (capturedThrowable != null) { if (exceptionMessage == null) { exceptionMessage = "Exception caught during test execution."; } ByteArrayOutputStream out = new ByteArrayOutputStream(); capturedThrowable.printStackTrace(new PrintStream(out)); logger.debug( "Setting test failed. Message: " + exceptionMessage + " Exception " + capturedThrowable); r.setFailed(exceptionMessage, capturedThrowable); } } if (!future.isDone()) { r.setFailed(JavalancheMessages.MUTATION_TIME_LIMIT_MESSAGE + "Mutated Thread is still running after timeout.", null); switchOfMutation(future); } stopWatch.stop(); if (!checkAllFinished(preIds)) { if (configuration.useThreadStop()) { stopThreads(preIds); } else { shutDown(r, stopWatch); } } logger.debug("End timed test, it took " + stopWatch.getTime() + " ms"); return stopWatch.getTime(); }
From source file:nl.strohalm.cyclos.utils.tasks.TaskRunnerImpl.java
protected void doRunInitialization(final String beanName) { final InitializingService service = applicationContext.getBean(beanName, InitializingService.class); getTransactionHelper().runInCurrentThread(new TransactionCallbackWithoutResult() { @Override/* ww w . j ava 2 s. c o m*/ protected void doInTransactionWithoutResult(final TransactionStatus status) { try { if (LOG.isDebugEnabled()) { LOG.debug("Running initialization for bean " + beanName); } LoggedUser.runAsSystem(Executors.callable(new Runnable() { @Override public void run() { service.initializeService(); } })); } catch (RuntimeException e) { LOG.error("Error running initialization for bean " + beanName, e); throw e; } } }); }
From source file:nl.strohalm.cyclos.utils.tasks.TaskRunnerImpl.java
private boolean doRunScheduledTask(final ScheduledTask task, final Calendar time) { try {//from w ww .ja v a2 s.c o m LoggedUser.runAsSystem(Executors.callable(new Runnable() { @Override public void run() { task.run(time); } })); return true; } catch (final Exception e) { LOG.error("Error running scheduled task " + task.getName(), e); return false; } }
From source file:ome.logic.UpdateImpl.java
@RolesAllowed("system") public void indexObject(IObject row) { if (row == null || row.getId() == null) { throw new ValidationException("Non-managed object cannot be indexed."); }//from w ww.ja v a2 s .co m CreationLogLoader logs = new CreationLogLoader(localQuery, row); FullTextIndexer fti = new FullTextIndexer(logs); final FullTextThread ftt = new FullTextThread(sessionManager, executor, fti, this.fullTextBridge, true); Future<Object> future = executor.submit(Executors.callable(ftt)); executor.get(future); }
From source file:omero.cmd.SessionI.java
public void submit_async(AMD_Session_submit __cb, omero.cmd.Request req, Ice.Current current) { try {//www .j a v a2 s . com if (req == null || !IRequest.class.isAssignableFrom(req.getClass())) { log.info("Non-IRequest found:" + req); __cb.ice_response(null); return; // EARLY EXIT } Ice.Object servant = null; for (String key : Arrays.asList(req.ice_id(), _HandleTie.ice_staticId())) { try { servant = createServantDelegate(key); if (servant != null && servant instanceof IHandle) { break; } } catch (Exception e) { log.debug(e.getClass().getName() + " on lookup of " + key); } } IHandle handle = null; if (servant != null) { if (servant instanceof Ice.TieBase) { Ice.TieBase tie = (Ice.TieBase) servant; Object delegate = tie.ice_delegate(); if (IHandle.class.isAssignableFrom(delegate.getClass())) { handle = (IHandle) delegate; } } else if (servant instanceof IHandle) { handle = (IHandle) servant; } } if (handle == null) { log.info("No handle found for " + req); InternalException ie = new InternalException(); ie.message = "No handle found for " + req; __cb.ice_exception(ie); return; // EARLY EXIT } // ID Ice.Identity id = holder.getIdentity("IHandle" + UUID.randomUUID().toString()); // Tie _HandleTie tie = (_HandleTie) servant; HandlePrx prx = HandlePrxHelper.checkedCast(registerServant(id, tie)); // Init try { handle.initialize(id, (IRequest) req, current.ctx); executor.submit(current.ctx, Executors.callable(handle)); __cb.ice_response(prx); } catch (Throwable e) { log.error("Exception on startup; removing handle " + id, e); unregisterServant(id); throw e; } } catch (Exception e) { log.error("Exception on " + req); __cb.ice_exception(e); } catch (Throwable t) { log.error("Throwable on " + req); RuntimeException rt = new RuntimeException("Throwable raised on " + req); rt.initCause(t); throw rt; } }
From source file:org.opennms.web.rest.UserRestServiceTest.java
@Test public void testWriteALotOfUsers() throws Exception { int userCount = 50; // Limit the thread pool so that we don't exhaust all of the database connections ExecutorService pool = Executors.newFixedThreadPool(25); List<Future<?>> createFutures = new ArrayList<Future<?>>(); for (int i = 0; i < userCount; i++) { final String userName = "test" + i; createFutures.add(pool.submit(Executors.callable(new Runnable() { @Override//from w w w.j av a 2s . c o m public void run() { try { createUser(userName, userName + "@opennms.org"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } }))); } // Wait for all of the REST operations to complete for (Future<?> future : createFutures) { future.get(); } // validate list OnmsUserList users = JaxbUtils.unmarshal(OnmsUserList.class, sendRequest(GET, "/users", 200)); assertNotNull(users); assertEquals(userCount + 1, users.size()); //+1 because user "admin" is there before creating all the new users. // Try changing the password for every user to make sure that they // are properly accessible in the UserManager for (int i = 0; i < userCount; i++) { // validate each created user String xml = sendRequest(GET, "/users/test" + i, 200); OnmsUser eachUser = JaxbUtils.unmarshal(OnmsUser.class, xml); assertEquals("test" + i, eachUser.getUsername()); assertEquals("test" + i + " Full Name", eachUser.getFullName()); assertEquals("test" + i + "@opennms.org", eachUser.getEmail()); assertEquals("Autogenerated by a unit test...", eachUser.getComments()); // change sendPut("/users/test" + i, "password=MONKEYS&email=TEST@OPENNMS.COM", 303, "/users/test" + i); // validate change of password eachUser = JaxbUtils.unmarshal(OnmsUser.class, sendRequest(GET, "/users/test" + i, 200)); User castorUser = getWebAppContext().getBean(UserManager.class).getUser("test" + i); assertEquals(castorUser.getPassword().getContent(), "MONKEYS"); // validate change of email assertEquals("TEST@OPENNMS.COM", eachUser.getEmail()); } }
From source file:org.opennms.web.rest.v1.UserRestServiceIT.java
@Test public void testWriteALotOfUsers() throws Exception { int userCount = 50; // Limit the thread pool so that we don't exhaust all of the database connections ExecutorService pool = Executors.newFixedThreadPool(25); List<Future<?>> createFutures = new ArrayList<Future<?>>(); for (int i = 0; i < userCount; i++) { final String userName = "test" + i; createFutures.add(pool.submit(Executors.callable(new Runnable() { @Override//www .ja v a 2s . c o m public void run() { try { setUser("admin", new String[] { "ROLE_ADMIN" }); createUser(userName, userName + "@opennms.org", 201, "/users/" + userName); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } }))); } // Wait for all of the REST operations to complete for (Future<?> future : createFutures) { future.get(); } // validate list OnmsUserList users = JaxbUtils.unmarshal(OnmsUserList.class, sendRequest(GET, "/users", 200)); assertNotNull(users); assertEquals(userCount + 1, users.size()); //+1 because user "admin" is there before creating all the new users. // Try changing the password for every user to make sure that they // are properly accessible in the UserManager for (int i = 0; i < userCount; i++) { // validate each created user String xml = sendRequest(GET, "/users/test" + i, 200); OnmsUser eachUser = JaxbUtils.unmarshal(OnmsUser.class, xml); assertEquals("test" + i, eachUser.getUsername()); assertEquals("test" + i + " Full Name", eachUser.getFullName()); assertEquals("test" + i + "@opennms.org", eachUser.getEmail()); assertEquals("Autogenerated by a unit test...", eachUser.getComments()); // change sendPut("/users/test" + i, "password=MONKEYS&email=TEST@OPENNMS.COM", 204); // validate change of password eachUser = JaxbUtils.unmarshal(OnmsUser.class, sendRequest(GET, "/users/test" + i, 200)); User castorUser = m_userManager.getUser("test" + i); assertEquals(castorUser.getPassword().getContent(), "MONKEYS"); // validate change of email assertEquals("TEST@OPENNMS.COM", eachUser.getEmail()); } }
From source file:pl.nask.hsn2.os.Main.java
private static void createConnectors(List<Callable<Object>> connectors, int count, String queueName) { for (int i = 0; i < count; i++) { ObjectStoreConnector connector = new ObjectStoreConnector(queueName, jobFinishedIgnore); connectors.add(Executors.callable(connector)); }/*from ww w . j av a 2s . c o m*/ }