Search in sources :

Example 61 with Callable

use of java.util.concurrent.Callable in project core-java by SpineEventEngine.

the class VerifyShould method fail_assertThrowsWithCause_if_callable_not_throws_exception_with_cause.

@Test(expected = AssertionError.class)
public void fail_assertThrowsWithCause_if_callable_not_throws_exception_with_cause() {
    final Callable notThrowsException = new Callable() {

        @Override
        public Object call() throws Exception {
            return null;
        }
    };
    assertThrowsWithCause(Exception.class, Exception.class, notThrowsException);
}
Also used : Callable(java.util.concurrent.Callable) Test(org.junit.Test)

Example 62 with Callable

use of java.util.concurrent.Callable in project voltdb by VoltDB.

the class SimpleTimeLimiter method newProxy.

@Override
public <T> T newProxy(final T target, Class<T> interfaceType, final long timeoutDuration, final TimeUnit timeoutUnit) {
    checkNotNull(target);
    checkNotNull(interfaceType);
    checkNotNull(timeoutUnit);
    checkArgument(timeoutDuration > 0, "bad timeout: %s", timeoutDuration);
    checkArgument(interfaceType.isInterface(), "interfaceType must be an interface type");
    final Set<Method> interruptibleMethods = findInterruptibleMethods(interfaceType);
    InvocationHandler handler = new InvocationHandler() {

        @Override
        public Object invoke(Object obj, final Method method, final Object[] args) throws Throwable {
            Callable<Object> callable = new Callable<Object>() {

                @Override
                public Object call() throws Exception {
                    try {
                        return method.invoke(target, args);
                    } catch (InvocationTargetException e) {
                        throw throwCause(e, false);
                    }
                }
            };
            return callWithTimeout(callable, timeoutDuration, timeoutUnit, interruptibleMethods.contains(method));
        }
    };
    return newProxy(interfaceType, handler);
}
Also used : Method(java.lang.reflect.Method) InvocationHandler(java.lang.reflect.InvocationHandler) Callable(java.util.concurrent.Callable) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 63 with Callable

use of java.util.concurrent.Callable in project voltdb by VoltDB.

the class ProcedureCallMicrobench method main.

public static void main(String[] args) throws Exception {
    int siteCount = 1;
    TPCCProjectBuilder pb = new TPCCProjectBuilder();
    pb.addDefaultSchema();
    pb.addDefaultPartitioning();
    pb.addProcedures(EmptyProcedure.class, MultivariateEmptyProcedure.class);
    pb.compile("procedureCallMicrobench.jar", siteCount, 0);
    ServerThread server = new ServerThread("procedureCallMicrobench.jar", BackendTarget.NATIVE_EE_JNI);
    server.start();
    server.waitForInitialization();
    int[] clientCounts = new int[] {};
    if (args.length >= 1 && !args[0].equals("${clients}")) {
        String[] clientCountString = args[0].split("\\s+");
        clientCounts = new int[clientCountString.length];
        for (int i = 0; i < clientCountString.length; i++) {
            clientCounts[i] = Integer.parseInt(clientCountString[i]);
        }
    }
    for (int clientCount : clientCounts) {
        for (int varmode = 0; varmode < 2; varmode++) {
            final Date date = new Date();
            final String name = varmode == 0 ? "EmptyProcedure" : "MultivariateEmptyProcedure";
            final Runner runner = varmode == 0 ? new Runner() {

                @Override
                public void run(Client client) throws Exception {
                    client.callProcedure(name, 0L);
                }
            } : new Runner() {

                @Override
                public void run(Client client) throws Exception {
                    client.callProcedure(name, 0L, 0L, 0L, "String c_first", "String c_middle", "String c_last", "String c_street_1", "String c_street_2", "String d_city", "String d_state", "String d_zip", "String c_phone", date, "String c_credit", 0.0, 0.0, 0.0, 0.0, 0L, 0L, "String c_data");
                }
            };
            // trigger classloading a couple times
            {
                ClientConfig config = new ClientConfig("program", "none");
                Client client = ClientFactory.createClient(config);
                client.createConnection("localhost");
                for (int i = 0; i < 10000; i++) client.callProcedure("EmptyProcedure", 0L);
            }
            ExecutorService executor = Executors.newFixedThreadPool(clientCount);
            ArrayList<Future<Integer>> futures = new ArrayList<Future<Integer>>(clientCount);
            final CyclicBarrier barrier = new CyclicBarrier(clientCount + 1);
            final long stopTime = System.currentTimeMillis() + 2000;
            for (int i = 0; i < clientCount; i++) {
                futures.add(executor.submit(new Callable<Integer>() {

                    public Integer call() {
                        try {
                            ClientConfig config = new ClientConfig("program", "none");
                            Client client = ClientFactory.createClient(config);
                            client.createConnection("localhost");
                            int count = 0;
                            barrier.await();
                            for (count = 0; count % 10 != 0 || System.currentTimeMillis() < stopTime; count++) {
                                runner.run(client);
                            }
                            return count;
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            throw new RuntimeException(ex);
                        }
                    }
                }));
            }
            barrier.await();
            final long startTime = System.currentTimeMillis();
            int count = 0;
            for (Future<Integer> future : futures) {
                count += future.get();
            }
            double time = stopTime - startTime;
            System.out.println(name + " with " + clientCount + " clients: " + count + " xacts in " + time + " ms => " + (time / count) + " ms/xact => " + (count / time) * 1000 + "tps");
        }
    }
    System.exit(0);
}
Also used : ArrayList(java.util.ArrayList) Date(java.util.Date) Callable(java.util.concurrent.Callable) CyclicBarrier(java.util.concurrent.CyclicBarrier) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) Client(org.voltdb.client.Client) ClientConfig(org.voltdb.client.ClientConfig) TPCCProjectBuilder(org.voltdb.benchmark.tpcc.TPCCProjectBuilder)

Example 64 with Callable

use of java.util.concurrent.Callable in project voltdb by VoltDB.

the class ClientInterface method initiateSnapshotDaemonWork.

@Override
public void initiateSnapshotDaemonWork(final String procedureName, long clientData, final Object[] params) {
    final Config sysProc = SystemProcedureCatalog.listing.get(procedureName);
    if (sysProc == null) {
        throw new RuntimeException("SnapshotDaemon attempted to invoke " + procedureName + " which is not a known procedure");
    }
    Procedure catProc = sysProc.asCatalogProcedure();
    StoredProcedureInvocation spi = new StoredProcedureInvocation();
    spi.setProcName(procedureName);
    spi.params = new FutureTask<ParameterSet>(new Callable<ParameterSet>() {

        @Override
        public ParameterSet call() {
            ParameterSet paramSet = ParameterSet.fromArrayWithCopy(params);
            return paramSet;
        }
    });
    spi.clientHandle = clientData;
    // Ugh, need to consolidate this with handleRead() somehow but not feeling it at the moment
    if (procedureName.equals("@SnapshotScan")) {
        InvocationDispatcher.dispatchStatistics(OpsSelector.SNAPSHOTSCAN, spi, m_snapshotDaemonAdapter);
        return;
    } else if (procedureName.equals("@SnapshotDelete")) {
        InvocationDispatcher.dispatchStatistics(OpsSelector.SNAPSHOTDELETE, spi, m_snapshotDaemonAdapter);
        return;
    }
    // initiate the transaction
    createTransaction(m_snapshotDaemonAdapter.connectionId(), spi, catProc.getReadonly(), catProc.getSinglepartition(), catProc.getEverysite(), 0, 0, System.nanoTime());
}
Also used : Config(org.voltdb.SystemProcedureCatalog.Config) Procedure(org.voltdb.catalog.Procedure) Callable(java.util.concurrent.Callable)

Example 65 with Callable

use of java.util.concurrent.Callable in project ACS by ACS-Community.

the class ServicesDaemonTest method testStartAcsServiceIndividually.

/**
	 * Simple test that only uses the start_xxx and Stop_xxx methods of the daemon,
	 * which is one step up from the old acsStart method, but does not use the convenience
	 * of the service description. All services are started on the same host. Later they are stopped.
	 */
public void testStartAcsServiceIndividually() throws Throwable {
    DaemonCallbackImpl daemonCallbackImpl_1 = new DaemonCallbackImpl(logger);
    DaemonCallbackImpl daemonCallbackImpl_2 = new DaemonCallbackImpl(logger);
    DaemonCallbackImpl daemonCallbackImpl_3 = new DaemonCallbackImpl(logger);
    DaemonCallback dcb_1 = activateDaemonCallback(daemonCallbackImpl_1);
    DaemonCallback dcb_2 = activateDaemonCallback(daemonCallbackImpl_2);
    DaemonCallback dcb_3 = activateDaemonCallback(daemonCallbackImpl_3);
    List<Throwable> thrs = new ArrayList<Throwable>();
    try {
        // start naming service and wait till it's up
        daemonCallbackImpl_1.prepareWaitForDone("naming");
        daemon.start_naming_service(dcb_1, instanceNumber);
        assertTrue("Failed to start naming service in 10 s", daemonCallbackImpl_1.waitForDone(10, TimeUnit.SECONDS));
        logger.info("Got naming service");
        // start interface repository but don't wait for it yet ( start other services in parallel)
        daemonCallbackImpl_2.prepareWaitForDone("IFR");
        daemon.start_interface_repository(true, true, dcb_2, instanceNumber);
        // start CDB and wait till it's up
        daemonCallbackImpl_1.prepareWaitForDone("CDB");
        // TODO try explicit path ($ACS_CDB replacement)
        daemon.start_xml_cdb(dcb_1, instanceNumber, false, "");
        assertTrue("Failed to start CDB in 15 s", daemonCallbackImpl_1.waitForDone(15, TimeUnit.SECONDS));
        assertCDB();
        // start manager and wait till it's up
        daemonCallbackImpl_1.prepareWaitForDone("manager");
        daemon.start_manager("", dcb_1, instanceNumber, false);
        assertTrue("Failed to start the ACS manager in 10 s", daemonCallbackImpl_1.waitForDone(10, TimeUnit.SECONDS));
        assertManager();
        // now wait for the IR if necessary
        assertTrue("Failed to start interface repository 30 s after all other services have started", daemonCallbackImpl_2.waitForDone(30, TimeUnit.SECONDS));
        logger.info("Got the IFR");
        // start 3 of the 4 known notify services in parallel.
        // We want to call the start_notification_service method in parallel, which yields an even more parallel service start
        // than with calling this asynchronous method 3 times in a sequence.
        // @TODO Currently this test fails due to what seems a deadlock in the daemon. With just one NC factory it works, but with 3 we get a timeout.
        daemonCallbackImpl_1.prepareWaitForDone("NC factory default");
        daemonCallbackImpl_2.prepareWaitForDone("NC factory logging");
        daemonCallbackImpl_3.prepareWaitForDone("NC factory alarms");
        class NotifySrvStarter implements Callable<Void> {

            private final String srvName;

            private final DaemonCallback cb;

            NotifySrvStarter(String srvName, DaemonCallback cb) {
                this.srvName = srvName;
                this.cb = cb;
            }

            public Void call() throws Exception {
                daemon.start_notification_service(srvName, cb, instanceNumber);
                return null;
            }
        }
        ExecutorService pool = Executors.newFixedThreadPool(3, new DaemonThreadFactory());
        Future<Void> defaultNotifSrvFuture = pool.submit(new NotifySrvStarter(systemNotificationServiceDefault.value, dcb_1));
        Future<Void> loggingNotifSrvFuture = pool.submit(new NotifySrvStarter(systemNotificationServiceLogging.value, dcb_2));
        Future<Void> alarmNotifSrvFuture = pool.submit(new NotifySrvStarter(systemNotificationServiceAlarms.value, dcb_3));
        try {
            defaultNotifSrvFuture.get(20, TimeUnit.SECONDS);
            loggingNotifSrvFuture.get(20, TimeUnit.SECONDS);
            alarmNotifSrvFuture.get(20, TimeUnit.SECONDS);
        } catch (ExecutionException ex) {
            // throw the ex that came from the call() method
            throw ex.getCause();
        } catch (TimeoutException ex2) {
            fail("Failed to return from 'start_notification_service' within 20 seconds. ");
        }
        // now wait for the notification services to be actually started
        daemonCallbackImpl_1.waitForDone(10, TimeUnit.SECONDS);
        daemonCallbackImpl_2.waitForDone(10, TimeUnit.SECONDS);
        daemonCallbackImpl_3.waitForDone(10, TimeUnit.SECONDS);
    } catch (Throwable thr) {
        thrs.add(thr);
    } finally {
        // and then waiting for the asynch calls to finish.
        try {
            daemonCallbackImpl_1.prepareWaitForDone("stop NC factory default");
            daemon.stop_notification_service(systemNotificationServiceDefault.value, dcb_1, instanceNumber);
        } catch (Throwable thr) {
            thrs.add(thr);
        }
        try {
            daemonCallbackImpl_2.prepareWaitForDone("stop NC factory logging");
            daemon.stop_notification_service(systemNotificationServiceLogging.value, dcb_2, instanceNumber);
        } catch (Throwable thr) {
            thrs.add(thr);
        }
        try {
            daemonCallbackImpl_3.prepareWaitForDone("stop NC factory alarms");
            daemon.stop_notification_service(systemNotificationServiceAlarms.value, dcb_3, instanceNumber);
        } catch (Throwable thr) {
            thrs.add(thr);
        }
        try {
            assertTrue("Failed to stop the default NC factory in 10 s", daemonCallbackImpl_1.waitForDone(10, TimeUnit.SECONDS));
            assertTrue("Failed to stop the logging NC factory in 10 s", daemonCallbackImpl_2.waitForDone(10, TimeUnit.SECONDS));
            assertTrue("Failed to stop the logging NC factory in 10 s", daemonCallbackImpl_3.waitForDone(10, TimeUnit.SECONDS));
        } catch (Throwable thr) {
            thrs.add(thr);
        }
        // stop the IFR
        try {
            daemonCallbackImpl_1.prepareWaitForDone("stop IFR");
            daemon.stop_interface_repository(dcb_1, instanceNumber);
            assertTrue("Failed to stop the interface repository in 10 s", daemonCallbackImpl_1.waitForDone(10, TimeUnit.SECONDS));
        } catch (Throwable thr) {
            thrs.add(thr);
        }
        // stop the manager
        try {
            daemonCallbackImpl_1.prepareWaitForDone("stop manager");
            daemon.stop_manager("", dcb_1, instanceNumber);
            assertTrue("Failed to stop the manager in 10 s", daemonCallbackImpl_1.waitForDone(10, TimeUnit.SECONDS));
        } catch (Throwable thr) {
            thrs.add(thr);
        }
    }
    if (thrs.size() > 0) {
        logger.info("Failure: there were " + thrs.size() + " errors.");
        throw thrs.get(0);
    }
}
Also used : DaemonThreadFactory(alma.acs.concurrent.DaemonThreadFactory) ArrayList(java.util.ArrayList) Callable(java.util.concurrent.Callable) DaemonCallback(alma.acsdaemon.DaemonCallback) ExecutorService(java.util.concurrent.ExecutorService) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

Callable (java.util.concurrent.Callable)1946 ArrayList (java.util.ArrayList)664 ExecutorService (java.util.concurrent.ExecutorService)630 Test (org.junit.Test)598 Future (java.util.concurrent.Future)482 IOException (java.io.IOException)255 ExecutionException (java.util.concurrent.ExecutionException)247 List (java.util.List)167 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)158 CountDownLatch (java.util.concurrent.CountDownLatch)157 HashMap (java.util.HashMap)120 Map (java.util.Map)117 File (java.io.File)112 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)105 Ignite (org.apache.ignite.Ignite)87 HashSet (java.util.HashSet)80 Set (java.util.Set)55 TimeoutException (java.util.concurrent.TimeoutException)54 Collectors (java.util.stream.Collectors)53 Transaction (org.apache.ignite.transactions.Transaction)52