Search in sources :

Example 1 with Suspendable

use of co.paralleluniverse.fibers.Suspendable in project quasar by puniverse.

the class ProxyServerTest method testCallOnVoidMethod.

@Test
public void testCallOnVoidMethod() throws Exception {
    final AtomicInteger called = new AtomicInteger(0);
    final Server<?, ?, ?> a = spawnServer(true, new A() {

        public int foo(String str, int x) {
            throw new UnsupportedOperationException();
        }

        @Suspendable
        public void bar(int x) {
            try {
                Strand.sleep(100);
                called.set(x);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (SuspendExecution e) {
                throw new AssertionError(e);
            }
        }
    });
    ((A) a).bar(15);
    assertThat(called.get(), is(15));
    a.shutdown();
    LocalActor.join(a, 100, TimeUnit.MILLISECONDS);
}
Also used : SuspendExecution(co.paralleluniverse.fibers.SuspendExecution) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Suspendable(co.paralleluniverse.fibers.Suspendable) Test(org.junit.Test)

Example 2 with Suspendable

use of co.paralleluniverse.fibers.Suspendable in project quasar by puniverse.

the class DynamicallyLoadedSuspendable method test.

@Suspendable
public void test(ArrayList<String> results) {
    results.add("a");
    TestInterface referencedSuspend = new ReferencedSuspendable();
    TestInterface2 indirectSuspend = new IndirectSuspendable();
    results.add("b");
    try {
        results.add("c");
        Fiber.park();
        results.add("d");
    } catch (SuspendExecution ex) {
    }
    results.add("e");
    referencedSuspend.test(results);
    results.add("f");
    indirectSuspend.test(results, referencedSuspend);
    results.add("g");
    while (true) {
        results.add("h");
        indirectSuspend.test(results, referencedSuspend);
        results.add("i");
    }
}
Also used : SuspendExecution(co.paralleluniverse.fibers.SuspendExecution) TestInterface(co.paralleluniverse.common.test.TestInterface) TestInterface2(co.paralleluniverse.common.test.TestInterface2) Suspendable(co.paralleluniverse.fibers.Suspendable)

Example 3 with Suspendable

use of co.paralleluniverse.fibers.Suspendable in project quasar by puniverse.

the class FiberFileChannel method open.

/**
     * Opens or creates a file for reading and/or writing, returning a file channel to access the file.
     *
     * <p>
     * The {@code options} parameter determines how the file is opened.
     * The {@link StandardOpenOption#READ READ} and {@link StandardOpenOption#WRITE
     * WRITE} options determines if the file should be opened for reading and/or
     * writing. If neither option is contained in the array then an existing file
     * is opened for reading.
     *
     * <p>
     * In addition to {@code READ} and {@code WRITE}, the following options
     * may be present:
     *
     * <table border=1 cellpadding=5 summary="">
     * <tr> <th>Option</th> <th>Description</th> </tr>
     * <tr>
     * <td> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </td>
     * <td> When opening an existing file, the file is first truncated to a
     * size of 0 bytes. This option is ignored when the file is opened only
     * for reading.</td>
     * </tr>
     * <tr>
     * <td> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </td>
     * <td> If this option is present then a new file is created, failing if
     * the file already exists. When creating a file the check for the
     * existence of the file and the creation of the file if it does not exist
     * is atomic with respect to other file system operations. This option is
     * ignored when the file is opened only for reading. </td>
     * </tr>
     * <tr>
     * <td > {@link StandardOpenOption#CREATE CREATE} </td>
     * <td> If this option is present then an existing file is opened if it
     * exists, otherwise a new file is created. When creating a file the check
     * for the existence of the file and the creation of the file if it does
     * not exist is atomic with respect to other file system operations. This
     * option is ignored if the {@code CREATE_NEW} option is also present or
     * the file is opened only for reading. </td>
     * </tr>
     * <tr>
     * <td > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </td>
     * <td> When this option is present then the implementation makes a
     * <em>best effort</em> attempt to delete the file when closed by the
     * the {@link #close close} method. If the {@code close} method is not
     * invoked then a <em>best effort</em> attempt is made to delete the file
     * when the Java virtual machine terminates. </td>
     * </tr>
     * <tr>
     * <td>{@link StandardOpenOption#SPARSE SPARSE} </td>
     * <td> When creating a new file this option is a <em>hint</em> that the
     * new file will be sparse. This option is ignored when not creating
     * a new file. </td>
     * </tr>
     * <tr>
     * <td> {@link StandardOpenOption#SYNC SYNC} </td>
     * <td> Requires that every update to the file's content or metadata be
     * written synchronously to the underlying storage device. (see <a
     * href="../file/package-summary.html#integrity"> Synchronized I/O file
     * integrity</a>). </td>
     * <tr>
     * <tr>
     * <td> {@link StandardOpenOption#DSYNC DSYNC} </td>
     * <td> Requires that every update to the file's content be written
     * synchronously to the underlying storage device. (see <a
     * href="../file/package-summary.html#integrity"> Synchronized I/O file
     * integrity</a>). </td>
     * </tr>
     * </table>
     *
     * <p>
     * An implementation may also support additional options.
     *
     * <p>
     * The {@code executor} parameter is the {@link ExecutorService} to
     * which tasks are submitted to handle I/O events and dispatch completion
     * results for operations initiated on resulting channel.
     * The nature of these tasks is highly implementation specific and so care
     * should be taken when configuring the {@code Executor}. Minimally it
     * should support an unbounded work queue and should not run tasks on the
     * caller thread of the {@link ExecutorService#execute execute} method.
     * Shutting down the executor service while the channel is open results in
     * unspecified behavior.
     *
     * <p>
     * The {@code attrs} parameter is an optional array of file {@link
     * FileAttribute file-attributes} to set atomically when creating the file.
     *
     * <p>
     * The new channel is created by invoking the {@link
     * FileSystemProvider#newFileChannel newFileChannel} method on the
     * provider that created the {@code Path}.
     *
     * @param path       The path of the file to open or create
     * @param options    Options specifying how the file is opened
     * @param ioExecutor The thread pool or {@code null} to associate the channel with the default thread pool
     * @param attrs      An optional list of file attributes to set atomically when creating the file
     *
     * @return A new file channel
     *
     * @throws IllegalArgumentException      If the set contains an invalid combination of options
     * @throws UnsupportedOperationException If the {@code file} is associated with a provider that does not
     *                                       support creating asynchronous file channels, or an unsupported
     *                                       open option is specified, or the array contains an attribute that
     *                                       cannot be set atomically when creating the file
     * @throws IOException                   If an I/O error occurs
     * @throws SecurityException             If a security manager is installed and it denies an
     *                                       unspecified permission required by the implementation.
     *                                       In the case of the default provider, the {@link SecurityManager#checkRead(String)}
     *                                       method is invoked to check read access if the file is opened for reading.
     *                                       The {@link SecurityManager#checkWrite(String)} method is invoked to check
     *                                       write access if the file is opened for writing
     */
@Suspendable
public static FiberFileChannel open(final ExecutorService ioExecutor, final Path path, final Set<? extends OpenOption> options, final FileAttribute<?>... attrs) throws IOException {
    // FiberAsyncIO.ioExecutor(); // 
    final ExecutorService ioExec = ioExecutor != null ? ioExecutor : fiberFileThreadPool;
    AsynchronousFileChannel afc = FiberAsyncIO.runBlockingIO(fiberFileThreadPool, new CheckedCallable<AsynchronousFileChannel, IOException>() {

        @Override
        public AsynchronousFileChannel call() throws IOException {
            return AsynchronousFileChannel.open(path, options, ioExec, attrs);
        }
    });
    return new FiberFileChannel(afc);
}
Also used : AsynchronousFileChannel(java.nio.channels.AsynchronousFileChannel) ExecutorService(java.util.concurrent.ExecutorService) IOException(java.io.IOException) Suspendable(co.paralleluniverse.fibers.Suspendable)

Example 4 with Suspendable

use of co.paralleluniverse.fibers.Suspendable in project quasar by puniverse.

the class Val method get.

/**
     * Returns the delayed value, blocking until it has been set, but no longer than the given timeout.
     *
     * @param timeout The maximum duration to block waiting for the value to be set.
     * @param unit    The time unit of the timeout value.
     * @return the value
     * @throws TimeoutException     if the timeout expires before the value is set.
     * @throws InterruptedException
     */
@Override
@Suspendable
public V get(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException {
    try {
        final SimpleConditionSynchronizer s = sync;
        if (s != null) {
            Object token = s.register();
            try {
                final long start = System.nanoTime();
                long left = unit.toNanos(timeout);
                final long deadline = start + left;
                for (int i = 0; sync != null; i++) {
                    s.awaitNanos(i, left);
                    if (sync == null)
                        break;
                    left = deadline - System.nanoTime();
                    if (left <= 0)
                        throw new TimeoutException();
                }
            } finally {
                s.unregister(token);
            }
        }
        if (t != null)
            throw t instanceof CancellationException ? (CancellationException) t : new RuntimeExecutionException(t);
        return value;
    } catch (SuspendExecution e) {
        throw new AssertionError(e);
    }
}
Also used : SimpleConditionSynchronizer(co.paralleluniverse.strands.SimpleConditionSynchronizer) SuspendExecution(co.paralleluniverse.fibers.SuspendExecution) CancellationException(java.util.concurrent.CancellationException) TimeoutException(java.util.concurrent.TimeoutException) RuntimeExecutionException(co.paralleluniverse.fibers.RuntimeExecutionException) Suspendable(co.paralleluniverse.fibers.Suspendable)

Example 5 with Suspendable

use of co.paralleluniverse.fibers.Suspendable in project quasar by puniverse.

the class CyclicBarrier method dowait.

/**
     * Main barrier code, covering the various policies.
     */
@Suspendable
private int dowait(boolean timed, long nanos) throws InterruptedException, BrokenBarrierException, TimeoutException {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        final Generation g = generation;
        if (g.broken)
            throw new BrokenBarrierException();
        if (Strand.interrupted()) {
            breakBarrier();
            throw new InterruptedException();
        }
        int index = --count;
        if (index == 0) {
            // tripped
            boolean ranAction = false;
            try {
                final Runnable command = barrierCommand;
                if (command != null)
                    command.run();
                ranAction = true;
                nextGeneration();
                return 0;
            } finally {
                if (!ranAction)
                    breakBarrier();
            }
        }
        // loop until tripped, broken, interrupted, or timed out
        for (; ; ) {
            try {
                if (!timed)
                    trip.await();
                else if (nanos > 0L)
                    nanos = trip.awaitNanos(nanos);
            } catch (InterruptedException ie) {
                if (g == generation && !g.broken) {
                    breakBarrier();
                    throw ie;
                } else {
                    // We're about to finish waiting even if we had not
                    // been interrupted, so this interrupt is deemed to
                    // "belong" to subsequent execution.
                    Strand.currentStrand().interrupt();
                }
            }
            if (g.broken)
                throw new BrokenBarrierException();
            if (g != generation)
                return index;
            if (timed && nanos <= 0L) {
                breakBarrier();
                throw new TimeoutException();
            }
        }
    } finally {
        lock.unlock();
    }
}
Also used : BrokenBarrierException(java.util.concurrent.BrokenBarrierException) TimeoutException(java.util.concurrent.TimeoutException) Suspendable(co.paralleluniverse.fibers.Suspendable)

Aggregations

Suspendable (co.paralleluniverse.fibers.Suspendable)7 SuspendExecution (co.paralleluniverse.fibers.SuspendExecution)5 TimeoutException (java.util.concurrent.TimeoutException)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 Test (org.junit.Test)2 TestInterface (co.paralleluniverse.common.test.TestInterface)1 TestInterface2 (co.paralleluniverse.common.test.TestInterface2)1 RuntimeExecutionException (co.paralleluniverse.fibers.RuntimeExecutionException)1 SimpleConditionSynchronizer (co.paralleluniverse.strands.SimpleConditionSynchronizer)1 IOException (java.io.IOException)1 AsynchronousFileChannel (java.nio.channels.AsynchronousFileChannel)1 BrokenBarrierException (java.util.concurrent.BrokenBarrierException)1 CancellationException (java.util.concurrent.CancellationException)1 ExecutorService (java.util.concurrent.ExecutorService)1