Search in sources :

Example 26 with FutureTask

use of java.util.concurrent.FutureTask in project android_frameworks_base by AOSPA.

the class ViewDebug method callMethodOnAppropriateTheadBlocking.

private static Object callMethodOnAppropriateTheadBlocking(final Method method, final Object object) throws IllegalAccessException, InvocationTargetException, TimeoutException {
    if (!(object instanceof View)) {
        return method.invoke(object, (Object[]) null);
    }
    final View view = (View) object;
    Callable<Object> callable = new Callable<Object>() {

        @Override
        public Object call() throws IllegalAccessException, InvocationTargetException {
            return method.invoke(view, (Object[]) null);
        }
    };
    FutureTask<Object> future = new FutureTask<Object>(callable);
    // Try to use the handler provided by the view
    Handler handler = view.getHandler();
    // Fall back on using the main thread
    if (handler == null) {
        handler = new Handler(android.os.Looper.getMainLooper());
    }
    handler.post(future);
    while (true) {
        try {
            return future.get(CAPTURE_TIMEOUT, java.util.concurrent.TimeUnit.MILLISECONDS);
        } catch (ExecutionException e) {
            Throwable t = e.getCause();
            if (t instanceof IllegalAccessException) {
                throw (IllegalAccessException) t;
            }
            if (t instanceof InvocationTargetException) {
                throw (InvocationTargetException) t;
            }
            throw new RuntimeException("Unexpected exception", t);
        } catch (InterruptedException e) {
        // Call get again
        } catch (CancellationException e) {
            throw new RuntimeException("Unexpected cancellation exception", e);
        }
    }
}
Also used : Handler(android.os.Handler) Callable(java.util.concurrent.Callable) InvocationTargetException(java.lang.reflect.InvocationTargetException) FutureTask(java.util.concurrent.FutureTask) CancellationException(java.util.concurrent.CancellationException) AccessibleObject(java.lang.reflect.AccessibleObject) ExecutionException(java.util.concurrent.ExecutionException)

Example 27 with FutureTask

use of java.util.concurrent.FutureTask in project opennms by OpenNMS.

the class NativeSocketTest method testServer.

@Test
public void testServer() throws Exception {
    String[] cmds = new String[] { "echo", "echo2", "quit" };
    DatagramSocket socket = null;
    try {
        socket = new DatagramSocket();
        for (final String cmd : cmds) {
            final DatagramSocket sock = socket;
            final FutureTask<DatagramPacket> task = new FutureTask<DatagramPacket>(new Callable<DatagramPacket>() {

                @Override
                public DatagramPacket call() throws Exception {
                    printf("Sending cmd: %s\n", cmd);
                    final byte[] data = cmd.getBytes(StandardCharsets.UTF_8);
                    final DatagramPacket p = new DatagramPacket(data, data.length, InetAddress.getLocalHost(), sock.getLocalPort());
                    sock.send(p);
                    printf("Receiving...\n");
                    final DatagramPacket r = new DatagramPacket(new byte[128], 128);
                    sock.receive(r);
                    printf("Received\n");
                    return r;
                }
            });
            m_executor.execute(task);
            final DatagramPacket r = task.get(10, TimeUnit.SECONDS);
            assertNotNull(r);
            final String response = new String(r.getData(), r.getOffset(), r.getLength(), StandardCharsets.UTF_8);
            printf("Received Response: %s from %s:%d\n", response, r.getAddress().getHostAddress(), r.getPort());
            assertEquals(cmd, response);
        }
    } finally {
        if (socket != null)
            socket.close();
    }
}
Also used : FutureTask(java.util.concurrent.FutureTask) DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket) Test(org.junit.Test)

Example 28 with FutureTask

use of java.util.concurrent.FutureTask in project android_frameworks_base by ResurrectionRemix.

the class MtpManagerTest method testCancelEvent.

public void testCancelEvent() throws Exception {
    final CancellationSignal signal = new CancellationSignal();
    final FutureTask<Boolean> future = new FutureTask<Boolean>(new Callable<Boolean>() {

        @Override
        public Boolean call() throws IOException {
            try {
                while (true) {
                    mManager.readEvent(mUsbDevice.getDeviceId(), signal);
                }
            } catch (OperationCanceledException exception) {
                return true;
            }
        }
    });
    final Thread thread = new Thread(future);
    thread.start();
    SystemClock.sleep(TIMEOUT_MS);
    signal.cancel();
    assertTrue(future.get(TIMEOUT_MS, TimeUnit.MILLISECONDS));
}
Also used : FutureTask(java.util.concurrent.FutureTask) OperationCanceledException(android.os.OperationCanceledException) IOException(java.io.IOException) CancellationSignal(android.os.CancellationSignal)

Example 29 with FutureTask

use of java.util.concurrent.FutureTask in project android_frameworks_base by ResurrectionRemix.

the class MffTestCase method setUp.

@Override
protected void setUp() throws Exception {
    super.setUp();
    // MffContext needs to be created on a separate thread to allow MFF to post Runnable's.
    mMffContextHandlerThread = new HandlerThread("MffContextThread");
    mMffContextHandlerThread.start();
    Handler handler = new Handler(mMffContextHandlerThread.getLooper());
    FutureTask<MffContext> task = new FutureTask<MffContext>(new Callable<MffContext>() {

        @Override
        public MffContext call() throws Exception {
            MffContext.Config config = new MffContext.Config();
            config.requireCamera = false;
            config.requireOpenGL = false;
            config.forceNoGL = true;
            return new MffContext(getContext(), config);
        }
    });
    handler.post(task);
    // Wait for the context to be created on the handler thread.
    mMffContext = task.get();
}
Also used : HandlerThread(android.os.HandlerThread) FutureTask(java.util.concurrent.FutureTask) Handler(android.os.Handler)

Example 30 with FutureTask

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

the class VoltNetwork method registerChannel.

/**
     * Register a channel with the selector and create a Connection that will pass incoming events
     * to the provided handler.
     * @param channel
     * @param handler
     * @throws IOException
     */
Connection registerChannel(final SocketChannel channel, final InputHandler handler, final int interestOps, final ReverseDNSPolicy dns, final CipherExecutor cipherService, final SSLEngine sslEngine) throws IOException {
    synchronized (channel.blockingLock()) {
        channel.configureBlocking(false);
        channel.socket().setKeepAlive(true);
    }
    Callable<Connection> registerTask = new Callable<Connection>() {

        @Override
        public Connection call() throws Exception {
            final VoltPort port = VoltPortFactory.createVoltPort(channel, VoltNetwork.this, handler, (InetSocketAddress) channel.socket().getRemoteSocketAddress(), m_pool, cipherService, sslEngine);
            port.registering();
            /*
                 * This means we are used by a client. No need to wait then, trigger
                 * the reverse DNS lookup now.
                 */
            if (dns != ReverseDNSPolicy.NONE) {
                port.resolveHostname(dns == ReverseDNSPolicy.SYNCHRONOUS);
            }
            try {
                SelectionKey key = channel.register(m_selector, interestOps, null);
                port.setKey(key);
                port.registered();
                //Fix a bug witnessed on the mini where the registration lock and the selector wakeup contained
                //within was not enough to prevent the selector from returning the port after it was registered,
                //but before setKey was called. Suspect a bug in the selector.wakeup() or register() implementation
                //on the mac.
                //The null check in invokeCallbacks will catch the null attachment, continue, and do the work
                //next time through the selection loop
                key.attach(port);
                return port;
            } finally {
                m_ports.add(port);
                m_numPorts.incrementAndGet();
            }
        }
    };
    FutureTask<Connection> ft = new FutureTask<Connection>(registerTask);
    m_tasks.offer(ft);
    m_selector.wakeup();
    try {
        return ft.get();
    } catch (Exception e) {
        throw new IOException(e);
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) FutureTask(java.util.concurrent.FutureTask) IOException(java.io.IOException) Callable(java.util.concurrent.Callable) AsynchronousCloseException(java.nio.channels.AsynchronousCloseException) CancelledKeyException(java.nio.channels.CancelledKeyException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException)

Aggregations

FutureTask (java.util.concurrent.FutureTask)111 ExecutionException (java.util.concurrent.ExecutionException)41 IOException (java.io.IOException)26 Test (org.junit.Test)24 Callable (java.util.concurrent.Callable)18 CountDownLatch (java.util.concurrent.CountDownLatch)18 ExecutorService (java.util.concurrent.ExecutorService)18 TimeoutException (java.util.concurrent.TimeoutException)13 Handler (android.os.Handler)12 ArrayList (java.util.ArrayList)12 InvocationTargetException (java.lang.reflect.InvocationTargetException)9 CancellationException (java.util.concurrent.CancellationException)8 AccessibleObject (java.lang.reflect.AccessibleObject)6 Future (java.util.concurrent.Future)6 FileNotFoundException (java.io.FileNotFoundException)5 InputStream (java.io.InputStream)5 Iterator (java.util.Iterator)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)5 CancellationSignal (android.os.CancellationSignal)4 OperationCanceledException (android.os.OperationCanceledException)4