Java Code Examples for java.util.concurrent.Callable

The following examples show how to use java.util.concurrent.Callable. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: development   Source File: SecurityInvocationHandlerTest.java    License: 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 2
Source Project: thorntail   Source File: CachingArtifactResolvingHelper.java    License: 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
/**
 * 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 4
@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 5
/**
 * 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 6
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 7
Source Project: RxJava3-preview   Source File: MaybeUsingTest.java    License: 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 8
Source Project: TakinRPC   Source File: ZkClient.java    License: 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 9
Source Project: data.int-map   Source File: Nodes.java    License: 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 10
/**
 * 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 11
Source Project: TencentKona-8   Source File: CAccessibility.java    License: 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 Project: development   Source File: ProductIT.java    License: 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 Project: buck   Source File: FakeTestRule.java    License: 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 Project: netbeans   Source File: ClassMemberPanelUI.java    License: 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 Project: development   Source File: BasicBillingProxy.java    License: 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
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 17
Source Project: TencentKona-8   Source File: Basic.java    License: 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 18
/**
 * {@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 19
Source Project: j2objc   Source File: ThreadPoolExecutorSubclassTest.java    License: 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 20
Source Project: brooklyn-server   Source File: EntityManagementUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static CreationResult<List<Entity>,List<String>> addChildrenStarting(final Entity parent, String yaml) {
    final List<Entity> children = addChildrenUnstarted(parent, yaml);
    String childrenCountString;

    int size = children.size();
    childrenCountString = size+" "+(size!=1 ? "children" : "child"); 

    TaskBuilder<List<String>> taskM = Tasks.<List<String>>builder().displayName("add children")
        .dynamic(true)
        .tag(BrooklynTaskTags.NON_TRANSIENT_TASK_TAG)
        .body(new Callable<List<String>>() {
            @Override public List<String> call() throws Exception {
                return ImmutableList.copyOf(Iterables.transform(children, EntityFunctions.id()));
            }})
            .description("Add and start "+childrenCountString);

    TaskBuilder<?> taskS = Tasks.builder().parallel(true).displayName("add (parallel)").description("Start each new entity");

    // autostart if requested
    for (Entity child: children) {
        if (child instanceof Startable) {
            taskS.add(Effectors.invocation(child, Startable.START, ImmutableMap.of("locations", ImmutableList.of())));
        } else {
            // include a task, just to give feedback in the GUI
            taskS.add(Tasks.builder().displayName("create").description("Skipping start (not a Startable Entity)")
                .body(Runnables.doNothing())
                .tag(BrooklynTaskTags.tagForTargetEntity(child))
                .build());
        }
    }
    taskM.add(taskS.build());
    Task<List<String>> task = Entities.submit(parent, taskM.build());

    return CreationResult.of(children, task);
}
 
Example 21
Source Project: ignite   Source File: GridEncryptionManager.java    License: 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 22
@Override
public void clear() {
    inGlobal(new Callable<Object>() {
        @Override public Object call() {
            sobj.clear(strict);
            return null;
        }
    });
}
 
Example 23
public static AccessibleText getAccessibleText(final Accessible a, final Component c) {
    if (a == null) return null;

    return invokeAndWait(new Callable<AccessibleText>() {
        public AccessibleText call() throws Exception {
            final AccessibleContext ac = a.getAccessibleContext();
            if (ac == null) return null;

            AccessibleText accessibleText = ac.getAccessibleText();
            return accessibleText;
        }
    }, c);
}
 
Example 24
static String getTextRange(final AccessibleEditableText aet, final int start, final int stop, final Component c) {
    if (aet == null) return null;

    return CAccessibility.invokeAndWait(new Callable<String>() {
        public String call() throws Exception {
            return aet.getTextRange(start, stop);
        }
    }, c);
}
 
Example 25
Source Project: kite   Source File: TestSchemaCommand.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMissingDatasetName() {
  TestHelpers.assertThrows("Should complain when no dataset name is given",
      IllegalArgumentException.class, new Callable<Void>() {
    @Override
    public Void call() throws Exception {
      command.run();
      return null;
    }
  });
  verifyZeroInteractions(console);
}
 
Example 26
Source Project: ans-android-sdk   Source File: AThreadPool.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 高优先级同步执行:主要时get类对外操作接口
 *
 * @param callable
 * @return
 */
public static Object syncHighPriorityExecutor(Callable callable) {
    Object object = null;
    FutureTask<Object> futureTask = new FutureTask<Object>(callable);
    highService.execute(futureTask);

    while (!futureTask.isDone() && !futureTask.isCancelled()) {
        try {
            object = futureTask.get();
        } catch (Throwable ignore) {
            ExceptionUtil.exceptionThrow(ignore);
        }
    }
    return object;
}
 
Example 27
Source Project: kripton   Source File: BindDeleteRawPersonDataSource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>Executes a transaction in async mode. This method <strong>is thread safe</strong> to avoid concurrent problems. The drawback is only one transaction at time can be executed. The database will be open in write mode. This method uses default error listener to intercept errors.</p>
 *
 * @param transaction
 * 	transaction to execute
 * @return <code>true</code> when transaction successful finished
 */
public Future<Boolean> executeAsync(final Transaction transaction) {
  return KriptonLibrary.getExecutorService().submit(new Callable<Boolean>() {
    @Override
    public Boolean call() throws Exception {
      return execute(transaction, onErrorListener);
    }
  });
}
 
Example 28
Source Project: netbeans   Source File: JndiResourcesModelImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <R> Future<R> runReadActionWhenReady(final MetadataModelAction<JndiResourcesModel, R> action) throws MetadataModelException, IOException {
    return getHelper().runJavaSourceTaskWhenScanFinished(new Callable<R>() {
        @Override
        public R call() throws Exception {
            return action.run(getModel());
        }
    });
}
 
Example 29
Source Project: knox   Source File: DeleteRows.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Callable<Response> callable() {
  return new Callable<Response>() {
    @Override
    public Response call() throws Exception {
      String rowsIdToQuery = rowsId;
      if( rowsIdToQuery == null || rowsIdToQuery.isEmpty() ) {
        rowsIdToQuery = "*";
      }

      StringBuilder columnsURIPart = new StringBuilder( "/" );
      if( column != null ) {
        columnsURIPart.append( column.toURIPart() );
      }
      columnsURIPart.append('/');

      String timeURIPart = "";
      if( time != null ) {
        timeURIPart = time.toString();
      }

      URIBuilder uri = uri( HBase.SERVICE_PATH, "/", tableName, "/", rowsIdToQuery, columnsURIPart.toString(), timeURIPart );
      HttpDelete delete = new HttpDelete( uri.build() );
      return new Response( execute( delete ) );
    }
  };
}
 
Example 30
Source Project: netbeans   Source File: SelectRootsPanel.java    License: Apache License 2.0 5 votes vote down vote up
/** Creates new form SelectSourcesPanel */
SelectRootsPanel (
        final int mode,
        @NonNull final URL root,
        @NonNull final List<? extends URI> attachedRoots,
        @NonNull final Callable<List<? extends String>> browseCall,
        @NonNull final Function<String, Collection<? extends URI>> convertor,
        @NullAllowed final SourceJavadocAttacherImplementation.Definer plugin) {
    assert (mode & ~1) == 0;
    assert root != null;
    assert browseCall != null;
    assert convertor != null;
    this.mode = mode;
    this.root = root;
    this.browseCall = browseCall;
    this.convertor = convertor;
    this.plugin = plugin;
    initComponents();
    final DefaultListModel<URI> model = new DefaultListModel<URI>();
    sources.setModel(model);
    sources.setCellRenderer(new RootRenderer());
    sources.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            enableSelectionSensitiveActions();
        }
    });
    for (URI r : attachedRoots)  {
        model.addElement(r);
    }
    addURL.setVisible(mode != 0);
    if (plugin != null) {
        download.setVisible(true);
        download.setToolTipText(plugin.getDescription());
    } else {
        download.setVisible(false);
    }
    enableSelectionSensitiveActions();
}