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: 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 #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: 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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #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: 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 #17
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 #18
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 #19
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 #20
Source File: EntityManagementUtils.java    From brooklyn-server with 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 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 #22
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 #23
Source File: CAccessibility.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
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
Source File: CAccessibleText.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
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 File: TestSchemaCommand.java    From kite with 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 File: AThreadPool.java    From ans-android-sdk with 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 File: BindDeleteRawPersonDataSource.java    From kripton with 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 File: JndiResourcesModelImpl.java    From netbeans with 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 File: DeleteRows.java    From knox with 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 File: SelectRootsPanel.java    From netbeans with 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();
}