java.util.concurrent.Callable Java Examples

The following examples show how to use java.util.concurrent.Callable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Basic.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * That method starts a set of threads, each thread sends a given number of
 * notifications.
 * The number of threads can be set via the attribute numOfNotificationSenders.
 * The number of notification sent by each thread can be set via
 * the attribute numOfNotificationSenderLoops.
 * Depending on the parameter customNotification we send either custom
 * notification(s) or MBeanServer registration and unregistration notification(s).
 * When customNotification=true the total number of notification(s) sent is
 * (numOfNotificationSenders * numOfNotificationSenderLoops). They are
 * sequentially of type NOTIF_TYPE_0 then NOTIF_TYPE_1 and so on.
 *
 * When customNotification=false the total number of notification(s) sent is
 * (numOfNotificationSenders * numOfNotificationSenderLoops) registration
 * notification(s)
 * +
 * (numOfNotificationSenders * numOfNotificationSenderLoops) unregistration
 * notification(s)
 *
 * @throws java.lang.Exception
 */
public void sendNotificationWave(boolean customNotification) throws
        Exception {
    // Build the set of notification sender.
    Collection<Callable<Integer>> tasks =
            new HashSet<Callable<Integer>>(numOfNotificationSenders);

    for (int i = 1; i <= numOfNotificationSenders; i++) {
        tasks.add(new NotifSender(numOfNotificationSenderLoops,
                customNotification, i));
    }

    // Start all notification sender in parallel.
    ExecutorService execServ = null;
    try {
        execServ = Executors.newFixedThreadPool(numOfNotificationSenders);
        List<Future<Integer>> taskHandlers = execServ.invokeAll(tasks);
        checkNotifSenderThreadStatus(taskHandlers);
    } finally {
        if (!execServ.isShutdown()) {
            execServ.shutdown();
        }
    }
}
 
Example #2
Source File: CachingArtifactResolvingHelper.java    From thorntail with Apache License 2.0 6 votes vote down vote up
private Set<ArtifactSpec> resolveInParallel(Collection<ArtifactSpec> toResolve) throws InterruptedException {
    ExecutorService threadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 10);
    List<Callable<ArtifactSpec>> callable = toResolve.stream()
            .map(spec -> (Callable<ArtifactSpec>) (() -> this.resolve(spec)))
            .collect(Collectors.toList());

    List<Future<ArtifactSpec>> futures = threadPool.invokeAll(
            callable
    );
    Set<ArtifactSpec> result = futures.stream()
            .map(this::safeGet)
            .filter(Objects::nonNull)
            .collect(Collectors.toSet());
    threadPool.shutdown();
    return result;
}
 
Example #3
Source File: SecurityInvocationHandlerTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    sessionContext = new TestSessionContext(null, null);
    callable = new Callable<Object>() {
        @Override
        public Void call() {
            return null;
        }
    };
    ctx = new IInvocationCtx() {
        @Override
        public TransactionManager getTransactionManager() {
            return null;
        }

        @Override
        public boolean isApplicationException(Exception e) {
            return false;
        }
    };
}
 
Example #4
Source File: ForkJoinPoolTest.java    From streamsupport with GNU General Public License v2.0 6 votes vote down vote up
/**
 * timed invokeAll(null time unit) throws NullPointerException
 */
public void testTimedInvokeAllNullTimeUnit() throws Throwable {
    ExecutorService e = new ForkJoinPool(1);
    PoolCleaner cleaner = null;
    try {
        cleaner = cleaner(e);
        List<Callable<String>> l = new ArrayList<>();
        l.add(new StringTask());
        try {
            e.invokeAll(l, randomTimeout(), null);
            shouldThrow();
        } catch (NullPointerException success) {}
    } finally {
        if (cleaner != null) {
            cleaner.close();
        }
    }
}
 
Example #5
Source File: SubscriptionDaoIT_Paging_Filtering_Supplier.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void getSubscriptionsForMyCustomersFilteredByServiceIDNoSubscriptionReturned()
        throws Exception {
    // given
    final String not_existing_service_id = "not existing";
    final int expected = 0;
    Set<Filter> filterSet = createFilterSet(null, null, null, null,
            not_existing_service_id);
    final Pagination pagination = createPagination(0,
            NUM_CUSTOMER_SUBSCRIPTIONS, null, filterSet);

    // when
    List<Subscription> result = runTX(new Callable<List<Subscription>>() {
        @Override
        public List<Subscription> call() throws Exception {
            return dao.getSubscriptionsForMyCustomers(supplierUser, states,
                    pagination);
        }
    });

    // then
    assertEquals(expected, result.size());
}
 
Example #6
Source File: JdbcThinTransactionsWithMvccEnabledSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Test that exception in one of the statements does not kill connection worker altogether.
 * @throws SQLException if failed.
 */
@Test
public void testExceptionHandling() throws SQLException {
    try (Connection c = c(true, NestedTxMode.ERROR)) {
        try (Statement s = c.createStatement()) {
            s.execute("INSERT INTO INTS(k, v) values(1, 1)");

            assertEquals(1, grid(0).cache("ints").get(1));

            GridTestUtils.assertThrows(null, new Callable<Void>() {
                @Override public Void call() throws Exception {
                    s.execute("INSERT INTO INTS(x, y) values(1, 1)");

                    return null;
                }
            }, SQLException.class, "Failed to parse query");

            s.execute("INSERT INTO INTS(k, v) values(2, 2)");

            assertEquals(2, grid(0).cache("ints").get(2));
        }
    }
}
 
Example #7
Source File: DefaultTaskInputs.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private Object unwrap(Object value) {
    while (true) {
        if (value instanceof Callable) {
            Callable callable = (Callable) value;
            try {
                value = callable.call();
            } catch (Exception e) {
                throw UncheckedException.throwAsUncheckedException(e);
            }
        } else if (value instanceof Closure) {
            Closure closure = (Closure) value;
            value = closure.call();
        } else if (value instanceof FileCollection) {
            FileCollection fileCollection = (FileCollection) value;
            return fileCollection.getFiles();
        } else {
            return value;
        }
    }
}
 
Example #8
Source File: MaybeUsingTest.java    From RxJava3-preview with Apache License 2.0 6 votes vote down vote up
@Test
public void errorNonEager() {

    Maybe.using(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            return 1;
        }
    }, new Function<Object, MaybeSource<Integer>>() {
        @Override
        public MaybeSource<Integer> apply(Object v) throws Exception {
            return Maybe.error(new TestException());
        }
    }, new Consumer<Object>() {
        @Override
        public void accept(Object d) throws Exception {

        }
    }, false)
    .test()
    .assertFailure(TestException.class);
}
 
Example #9
Source File: ZkClient.java    From TakinRPC with Apache License 2.0 6 votes vote down vote up
public boolean delete(final String path) {
    try {
        retryUntilConnected(new Callable<byte[]>() {

            @Override
            public byte[] call() throws Exception {
                _connection.delete(path);
                return null;
            }
        });

        return true;
    } catch (ZkNoNodeException e) {
        return false;
    }
}
 
Example #10
Source File: Nodes.java    From data.int-map with Eclipse Public License 1.0 6 votes vote down vote up
public Object fold(final long n, final IFn combiner, final IFn reducer, final IFn fjtask, final IFn fjfork, final IFn fjjoin) {
  if (n > count()) {
    List<Callable> tasks = new ArrayList();
    for (int i = 0; i < 16; i++) {
      final INode node = children[i];
      if (node != null) {
        tasks.add(new Callable() {
          public Object call() throws Exception {
            return node.fold(n, combiner, reducer, fjtask, fjfork, fjjoin);
          }
        });
      }
    }
    return foldTasks(tasks, combiner, fjtask, fjfork, fjjoin);
  } else {
    return kvreduce(reducer, combiner.invoke());
  }
}
 
Example #11
Source File: CAccessibility.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static Object[] getChildren(final Accessible a, final Component c) {
    if (a == null) return null;
    return invokeAndWait(new Callable<Object[]>() {
        public Object[] call() throws Exception {
            final AccessibleContext ac = a.getAccessibleContext();
            if (ac == null) return null;

            final int numChildren = ac.getAccessibleChildrenCount();
            final Object[] children = new Object[numChildren];
            for (int i = 0; i < numChildren; i++) {
                children[i] = ac.getAccessibleChild(i);
            }
            return children;
        }
    }, c);
}
 
Example #12
Source File: ProductIT.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * <b>Testcase:</b> Add new Product objects <br>
 * <b>ExpectedResult:</b>
 * <ul>
 * <li>All objects can be retrieved from DB and are identical to provided
 * Product objects</li>
 * <li>Cascaded objects (i.e. PriceModel) is also stored</li>
 * <li>A history object is created for each product stored</li>
 * <li>History objects are created for CascadeAudit-annotated associated
 * objects</li>
 * </ul>
 * 
 * @throws Throwable
 */
@Test
public void testAdd() throws Throwable {
    try {
        runTX(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                doTestAdd();
                return null;
            }
        });
        runTX(new Callable<Void>() {
            @Override
            public Void call() {
                doTestAddCheck();
                return null;
            }
        });
    } catch (EJBException e) {
        throw e.getCause();
    }
}
 
Example #13
Source File: FakeTestRule.java    From buck with Apache License 2.0 6 votes vote down vote up
public FakeTestRule(
    BuildTarget buildTarget,
    ProjectFilesystem projectFilesystem,
    BuildRuleParams buildRuleParams,
    ImmutableSet<String> labels,
    Optional<Path> pathToTestOutputDirectory,
    boolean runTestSeparately,
    ImmutableList<Step> testSteps,
    Callable<TestResults> interpretedTestResults) {
  super(buildTarget, projectFilesystem, buildRuleParams);
  this.labels = labels;
  this.pathToTestOutputDirectory = pathToTestOutputDirectory;
  this.runTestSeparately = runTestSeparately;
  this.testSteps = testSteps;
  this.interpretedTestResults = interpretedTestResults;
}
 
Example #14
Source File: ClassMemberPanelUI.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private ElementJavadoc getJavaDocFor(
        @NonNull final ElementNode node,
        @NullAllowed final Callable<Boolean> cancel) {
    ElementNode root = getRootNode();
    if ( root == null ) {
        return null;
    }
    final ElementHandle<? extends Element> eh = node.getDescritption().getElementHandle();
    if (eh == null) {
        return null;
    }
    final JavaSource js = JavaSource.forFileObject( root.getDescritption().fileObject );
    if (js == null) {
        return null;
    }
    final JavaDocCalculator calculator = new JavaDocCalculator(eh, cancel);
    try {
        js.runUserActionTask( calculator, true );
    } catch( IOException ioE ) {
        Exceptions.printStackTrace( ioE );
        return null;
    }
    return calculator.doc;
}
 
Example #15
Source File: BasicBillingProxy.java    From development with Apache License 2.0 6 votes vote down vote up
<T> Future<T> submitAdapterCall(Callable<T> callable)
        throws BillingApplicationException {
    ExecutorService executor = getSingleThreadExecutor();

    Future<T> future = null;
    try {
        future = executor.submit(callable);
    } catch (RejectedExecutionException e) {
        logger.logError(Log4jLogger.SYSTEM_LOG, e,
                LogMessageIdentifier.ERROR_EXECUTION_OF_BILLING_APPLICATION_TASK_REJECTED);
        throw new BillingApplicationException(
                "Call to Billing Adapter failed",
                new BillingAdapterConnectionException(
                        "The execution of the billing application task was rejected"));
    }

    return future;
}
 
Example #16
Source File: JpaPersistenceProvider.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@Transactional
public <T> void deleteAll(final Class<T> type) {
    doWithExceptionTranslation(new Callable<Object>() {
        @Override
        public Object call() {
            new JpaCriteriaQuery(getSharedEntityManager()).deleteAll(type);
// If the L2 cache is enabled, items will still be served from the cache
// So, we need to flush that as well for the given type
if (sharedEntityManager.getEntityManagerFactory().getCache() != null) {
	sharedEntityManager.getEntityManagerFactory().getCache().evict(type);
}
            return null;
        }
    });
}
 
Example #17
Source File: ConcurrentRepositoryTest.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Returns a Callable that calls {@link Folder#refresh()}
 */
private Callable<Void> folder_refresh(final Folder folder) {
	return new Callable<Void>() {

		@Override
		public Void call() {
			try {
				startSignal.await();
				Thread.sleep(random.nextInt(THREAD_WAIT_THRESHOLD));
				// System.out.println(Thread.currentThread().getName() + " RERESH");
				folder.refresh();
			} catch (RepositoryException | InterruptedException e) {
				Assert.fail(Thread.currentThread().getName() + " " + e.getMessage());
			}
			return null;
		}
	};
}
 
Example #18
Source File: ThreadPoolExecutorSubclassTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * invokeAny(c) throws ExecutionException if no task completes
 */
public void testInvokeAny4() throws Exception {
    final ExecutorService e =
        new CustomTPE(2, 2,
                      LONG_DELAY_MS, MILLISECONDS,
                      new ArrayBlockingQueue<Runnable>(10));
    try (PoolCleaner cleaner = cleaner(e)) {
        List<Callable<String>> l = new ArrayList<Callable<String>>();
        l.add(new NPETask());
        try {
            e.invokeAny(l);
            shouldThrow();
        } catch (ExecutionException success) {
            assertTrue(success.getCause() instanceof NullPointerException);
        }
    }
}
 
Example #19
Source File: RemotePluginCommunicationHelper.java    From Easer with GNU General Public License v3.0 6 votes vote down vote up
public void asyncRemoteEditOperationData(final String id, OnEditDataIntentObtainedCallback onEditDataIntentObtainedCallback) {
    ParcelUuid uuid = onEditDataIntentObtainedCallbackCallbackStore.putCallback(onEditDataIntentObtainedCallback);
    doAfterConnect(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            Message message = Message.obtain();
            message.what = C.MSG_EDIT_OPERATION_DATA;
            message.replyTo = inMessenger;
            Bundle bundle = new Bundle();
            bundle.putString(C.EXTRA_PLUGIN_ID, id);
            bundle.putParcelable(C.EXTRA_MESSAGE_ID, uuid);
            message.setData(bundle);
            outMessenger.send(message);
            return null;
        }
    });
}
 
Example #20
Source File: TestUnsupportedVM.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void assertIOException(Callable<?> c) {
    try {
        c.call();
    } catch (Exception e) {
        if (e.getClass() == IOException.class) {
            return;
        }
    }
    throw new AssertionError("Expected IOException on an unsupported JVM");
}
 
Example #21
Source File: MainController.java    From android-uiconductor with Apache License 2.0 5 votes vote down vote up
@CrossOrigin(origins = "*")
@RequestMapping(value = "/playAction", method = RequestMethod.POST)
public Callable<String> playAction(@RequestBody PlayActionRequest playActionRequest) {
  return () ->
      workflowManager.playAction(
          playActionRequest.getActionId(), playActionRequest.getPlaySpeedFactor());
}
 
Example #22
Source File: AnnotationScannerTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testScanTypes() throws Exception {
    TestUtilities.copyStringToFileObject(srcFO, "Customer.java",
            "@javax.persistence.Entity()" +
            "public class Customer { }");
    TestUtilities.copyStringToFileObject(srcFO, "Foo.java",
            "public class Foo { }");
    TestUtilities.copyStringToFileObject(srcFO, "Item.java",
            "@javax.persistence.Entity()" +
            "public class Item { }");
    IndexingManager.getDefault().refreshIndexAndWait(srcFO.getURL(), null);
    ClasspathInfo cpi = ClasspathInfo.create(srcFO);
    final AnnotationModelHelper helper = AnnotationModelHelper.create(cpi);
    final Set<String> types = new HashSet<String>();
    helper.runJavaSourceTask(new Callable<Void>() {
        public Void call() throws InterruptedException {
            helper.getAnnotationScanner().findAnnotations("javax.persistence.Entity", AnnotationScanner.TYPE_KINDS, new AnnotationHandler() {
                public void handleAnnotation(TypeElement type, Element element, AnnotationMirror annotation) {
                    types.add(type.getQualifiedName().toString());
                }
            });
            return null;
        }
    });
    assertEquals(2, types.size());
    assertTrue(types.contains("Customer"));
    assertTrue(types.contains("Item"));
}
 
Example #23
Source File: GridEncryptionManager.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param c Callable to run with master key change read lock.
 * @return Computed result.
 */
private <T> T withMasterKeyChangeReadLock(Callable<T> c) {
    masterKeyChangeLock.readLock().lock();

    try {
        return c.call();
    }
    catch (Exception e) {
        throw new IgniteException(e);
    }
    finally {
        masterKeyChangeLock.readLock().unlock();
    }
}
 
Example #24
Source File: ScriptObjectMirror.java    From nashorn with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void putAll(final Map<? extends String, ? extends Object> map) {
    final ScriptObject oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != global);
    inGlobal(new Callable<Object>() {
        @Override public Object call() {
            for (final Map.Entry<? extends String, ? extends Object> entry : map.entrySet()) {
                final Object value = entry.getValue();
                final Object modValue = globalChanged? wrap(value, oldGlobal) : value;
                sobj.set(entry.getKey(), unwrap(modValue, global), strict);
            }
            return null;
        }
    });
}
 
Example #25
Source File: ScriptObjectMirror.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Utilitity to convert this script object to the given type.
 *
 * @param type destination type to convert to
 * @return converted object
 */
public <T> T to(final Class<T> type) {
    return inGlobal(new Callable<T>() {
        @Override
        public T call() {
            return type.cast(ScriptUtils.convert(sobj, type));
        }
    });
}
 
Example #26
Source File: IndexFreeQueryEngineTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
private <T> T expectFullCollectionQuery(Callable<T> c) throws Exception {
  try {
    expectIndexFreeExecution = false;
    return c.call();
  } finally {
    expectIndexFreeExecution = null;
  }
}
 
Example #27
Source File: RefreshScopePureScaleTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Test
@Repeat(10)
@DirtiesContext
public void testConcurrentRefresh() throws Exception {

	// overload the thread pool and try to force Spring to create too many instances
	int n = 80;
	this.scope.refreshAll();
	final CountDownLatch latch = new CountDownLatch(n);
	List<Future<String>> results = new ArrayList<>();
	for (int i = 0; i < n; i++) {
		results.add(this.executor.submit(new Callable<String>() {
			@Override
			public String call() throws Exception {
				logger.debug("Background started.");
				try {
					return RefreshScopePureScaleTests.this.service.getMessage();
				}
				finally {
					latch.countDown();
					logger.debug("Background done.");
				}
			}
		}));
		this.executor.submit(new Runnable() {
			@Override
			public void run() {
				logger.debug("Refreshing.");
				RefreshScopePureScaleTests.this.scope.refreshAll();
			}
		});
	}
	then(latch.await(15000, TimeUnit.MILLISECONDS)).isTrue();
	then(this.service.getMessage()).isEqualTo("Foo");
	for (Future<String> result : results) {
		then(result.get()).isEqualTo("Foo");
	}
}
 
Example #28
Source File: BackendTransaction.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
public EntryList indexQuery(KeySliceQuery query) {
    return executeRead(new Callable<EntryList>() {
        @Override
        public EntryList call() throws Exception {
            return cacheEnabled ? indexStore.getSlice(query, storeTx) : indexStore.getSliceNoCache(query, storeTx);
        }

        @Override
        public String toString() {
            return "VertexIndexQuery";
        }
    });

}
 
Example #29
Source File: ScriptObjectMirror.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void clear() {
    inGlobal(new Callable<Object>() {
        @Override public Object call() {
            sobj.clear(strict);
            return null;
        }
    });
}
 
Example #30
Source File: StitchAppClientImpl.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public Task<Void> callFunction(
    final String name,
    final List<?> args) {
  return dispatcher.dispatchTask(
      new Callable<Void>() {
        @Override
        public Void call() {
          coreClient.callFunction(name, args, null);
          return null;
        }
      });
}