类java.util.concurrent.Callable源码实例Demo

下面列出了怎么用java.util.concurrent.Callable的API类实例代码及写法,或者点击链接到github查看源代码。

@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;
        }
    };
}
 
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;
}
 
源代码3 项目: streamsupport   文件: ForkJoinPoolTest.java
/**
 * 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();
        }
    }
}
 
@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());
}
 
/**
 * 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));
        }
    }
}
 
源代码6 项目: Pushjet-Android   文件: DefaultTaskInputs.java
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;
        }
    }
}
 
源代码7 项目: RxJava3-preview   文件: MaybeUsingTest.java
@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);
}
 
源代码8 项目: TakinRPC   文件: ZkClient.java
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;
    }
}
 
源代码9 项目: data.int-map   文件: Nodes.java
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());
  }
}
 
/**
 * 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;
		}
	};
}
 
源代码11 项目: TencentKona-8   文件: CAccessibility.java
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);
}
 
源代码12 项目: development   文件: ProductIT.java
/**
 * <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();
    }
}
 
源代码13 项目: buck   文件: FakeTestRule.java
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;
}
 
源代码14 项目: netbeans   文件: ClassMemberPanelUI.java
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;
}
 
源代码15 项目: development   文件: BasicBillingProxy.java
<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;
}
 
源代码16 项目: Easer   文件: RemotePluginCommunicationHelper.java
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;
        }
    });
}
 
源代码17 项目: TencentKona-8   文件: Basic.java
/**
 * 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();
        }
    }
}
 
源代码18 项目: rice   文件: JpaPersistenceProvider.java
/**
 * {@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;
        }
    });
}
 
源代码19 项目: j2objc   文件: ThreadPoolExecutorSubclassTest.java
/**
 * 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);
        }
    }
}
 
源代码20 项目: brooklyn-server   文件: EntityManagementUtils.java
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);
}
 
源代码21 项目: ignite   文件: GridEncryptionManager.java
/**
 * @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();
    }
}
 
源代码22 项目: TencentKona-8   文件: ScriptObjectMirror.java
@Override
public void clear() {
    inGlobal(new Callable<Object>() {
        @Override public Object call() {
            sobj.clear(strict);
            return null;
        }
    });
}
 
源代码23 项目: dragonwell8_jdk   文件: CAccessibility.java
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);
}
 
源代码24 项目: dragonwell8_jdk   文件: CAccessibleText.java
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);
}
 
源代码25 项目: kite   文件: TestSchemaCommand.java
@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);
}
 
源代码26 项目: ans-android-sdk   文件: AThreadPool.java
/**
 * 高优先级同步执行:主要时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;
}
 
源代码27 项目: kripton   文件: BindDeleteRawPersonDataSource.java
/**
 * <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);
    }
  });
}
 
源代码28 项目: netbeans   文件: JndiResourcesModelImpl.java
@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());
        }
    });
}
 
源代码29 项目: knox   文件: DeleteRows.java
@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 ) );
    }
  };
}
 
源代码30 项目: netbeans   文件: SelectRootsPanel.java
/** 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();
}
 
 类所在包
 类方法
 同包方法