Search in sources :

Example 1 with Actor

use of co.paralleluniverse.actors.Actor in project quasar by puniverse.

the class PeerTKB method run.

public void run() throws ExecutionException, InterruptedException {
    switch(SCENARIO.testGenEvent) {
        case test:
            final Store store = Grid.getInstance().store();
            if (i == 1) {
                StoreTransaction tx = store.beginTransaction();
                try {
                    long root = store.getRoot("root", tx);
                    // "hello".getBytes();
                    byte[] buf = null;
                    store.set(root, buf, tx);
                    store.commit(tx);
                } catch (TimeoutException ex) {
                    throw new RuntimeException("set failed");
                }
                Thread.sleep(20000);
            } else {
                StoreTransaction tx = store.beginTransaction();
                byte[] get;
                try {
                    long root = store.getRoot("root", tx);
                    get = store.get(root);
                    store.commit(tx);
                } catch (TimeoutException ex) {
                    throw new RuntimeException("get failed");
                }
                System.out.println(get);
            }
            break;
        case testGenServer:
            if (i == 1) {
                spawnGenServer(new AbstractServerHandler<Message, Integer, Message>() {

                    @Override
                    public void init() throws SuspendExecution {
                        super.init();
                        ServerActor.currentServerActor().register("myServer");
                    }

                    @Override
                    public Integer handleCall(ActorRef<?> from, Object id, Message m) {
                        return m.a + m.b;
                    }
                }).join();
            } else {
                Integer get = spawnActor(new BasicActor<Message, Integer>(new MailboxConfig(10, Channels.OverflowPolicy.THROW)) {

                    protected Integer doRun() throws SuspendExecution, InterruptedException {
                        final Server<Message, Integer, Message> gs = (Server) ActorRegistry.getActor("myServer");
                        return gs.call(new Message(3, 4));
                    }
                }).get();
                System.out.println("value is " + get);
                assert get == 7;
            }
            break;
        case testGenEvent:
            if (i == 1) {
                final Val<String> dv = new Val<>();
                spawnGenEvent(new Initializer() {

                    @Override
                    public void init() throws SuspendExecution {
                        EventSourceActor.currentEventSourceActor().register("myEventServer");
                        try {
                            final EventSource<String> ge = LocalActor.self();
                            ge.addHandler(new EventHandler<String>() {

                                @Override
                                public void handleEvent(String event) {
                                    dv.set(event);
                                    System.out.println("sout " + event);
                                    ge.shutdown();
                                }
                            });
                        } catch (InterruptedException ex) {
                            System.out.println(ex);
                        }
                    }

                    @Override
                    public void terminate(Throwable cause) throws SuspendExecution {
                        System.out.println("terminated");
                    }
                });
                String get = dv.get();
                System.out.println("got msg " + get);
                assert get.equals("hello world");
            } else {
                spawnActor(new BasicActor<Message, Void>() {

                    protected Void doRun() throws SuspendExecution, InterruptedException {
                        final EventSource<String> ge = (EventSource) ActorRegistry.getActor("myEventServer");
                        ge.notify("hello world");
                        return null;
                    }
                }).join();
            }
            break;
        case testMultiGetActor:
            if (i == 1) {
                spawnGenEvent(new Initializer() {

                    AtomicInteger ai = new AtomicInteger();

                    @Override
                    public void init() throws SuspendExecution {
                        Actor.currentActor().register("myEventServer");
                        try {
                            final EventSource<String> ge = LocalActor.self();
                            ge.addHandler(new EventHandler<String>() {

                                @Override
                                public void handleEvent(String event) {
                                    System.out.println("msg no " + ai.incrementAndGet() + ": " + event);
                                }
                            });
                        } catch (InterruptedException ex) {
                            System.out.println(ex);
                        }
                    }

                    @Override
                    public void terminate(Throwable cause) throws SuspendExecution {
                        System.out.println("terminated");
                    }
                }).join();
            } else {
                Queue<Actor> queue = new LinkedList<>();
                for (int j = 0; j < 1000; j++) {
                    final BasicActor<Message, Void> actor = spawnActor(new BasicActor<Message, Void>("actor-" + j) {

                        protected Void doRun() throws SuspendExecution, InterruptedException {
                            try {
                                final EventSource<String> ge = (EventSource) ActorRegistry.getActor("myEventServer");
                                ge.notify("hwf " + getName());
                            } catch (Exception e) {
                                System.out.println("error in " + getName());
                                throw e;
                            }
                            return null;
                        }
                    });
                    queue.add(actor);
                // actor.join();
                }
                for (Actor localActor : queue) localActor.join();
                Thread.sleep(500);
            }
            break;
        case testOrdering:
            if (i == 1) {
                spawnGenEvent(new Initializer() {

                    AtomicInteger ai = new AtomicInteger();

                    @Override
                    public void init() throws SuspendExecution {
                        EventSourceActor.currentEventSourceActor().register("myEventServer");
                        try {
                            EventSourceActor<String> ge = EventSourceActor.currentEventSourceActor();
                            ge.ref().addHandler(new EventHandler<String>() {

                                @Override
                                public void handleEvent(String event) {
                                    System.out.println("msg no " + ai.incrementAndGet() + ": " + event);
                                }
                            });
                        } catch (InterruptedException ex) {
                            System.out.println(ex);
                        }
                    }

                    @Override
                    public void terminate(Throwable cause) throws SuspendExecution {
                        System.out.println("terminated");
                    }
                }).join();
            } else {
                Queue<Actor> queue = new LinkedList<>();
                for (int j = 0; j < 1; j++) {
                    final BasicActor<Message, Void> actor = spawnActor(new BasicActor<Message, Void>("actor-" + j) {

                        protected Void doRun() throws SuspendExecution, InterruptedException {
                            try {
                                final EventSource<String> ge = (EventSource) ActorRegistry.getActor("myEventServer");
                                for (int k = 0; k < 3000; k++) ge.notify("hw " + k + " f" + getName());
                            } catch (Exception e) {
                                System.out.println("error in " + getName());
                                throw e;
                            }
                            return null;
                        }
                    });
                    queue.add(actor);
                // actor.join();
                }
                for (Actor localActor : queue) localActor.join();
                Thread.sleep(5000);
            }
            break;
        default:
    }
    System.out.println("finished");
    System.exit(0);
    while (true) {
        System.out.println("==================");
        ThreadUtil.dumpThreads();
        Thread.sleep(5000);
    }
}
Also used : Val(co.paralleluniverse.strands.dataflow.Val) Server(co.paralleluniverse.actors.behaviors.Server) StoreTransaction(co.paralleluniverse.galaxy.StoreTransaction) ActorRef(co.paralleluniverse.actors.ActorRef) Store(co.paralleluniverse.galaxy.Store) EventHandler(co.paralleluniverse.actors.behaviors.EventHandler) MailboxConfig(co.paralleluniverse.actors.MailboxConfig) LocalActor(co.paralleluniverse.actors.LocalActor) BasicActor(co.paralleluniverse.actors.BasicActor) EventSourceActor(co.paralleluniverse.actors.behaviors.EventSourceActor) Actor(co.paralleluniverse.actors.Actor) ServerActor(co.paralleluniverse.actors.behaviors.ServerActor) AbstractServerHandler(co.paralleluniverse.actors.behaviors.AbstractServerHandler) TimeoutException(co.paralleluniverse.galaxy.TimeoutException) SuspendExecution(co.paralleluniverse.fibers.SuspendExecution) BasicActor(co.paralleluniverse.actors.BasicActor) LinkedList(java.util.LinkedList) TimeoutException(co.paralleluniverse.galaxy.TimeoutException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) EventSource(co.paralleluniverse.actors.behaviors.EventSource) Initializer(co.paralleluniverse.actors.behaviors.Initializer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 2 with Actor

use of co.paralleluniverse.actors.Actor in project quasar by puniverse.

the class SupervisorActor method start.

private ActorRef<?> start(ChildEntry child) throws SuspendExecution {
    final ActorRef old = child.actor;
    if (old != null && !LocalActor.isDone(old))
        throw new IllegalStateException("Actor " + child.actor + " cannot be restarted because it is not dead");
    final Actor actor = child.spec.builder.build();
    if (actor.getName() == null && child.spec.id != null)
        actor.setName(child.spec.id);
    log().info("{} starting child {}", this, actor);
    if (old != null && actor.getMonitor() == null && isLocal(old) && LocalActor.getMonitor(old) != null)
        actor.setMonitor(LocalActor.getMonitor(old));
    if (actor.getMonitor() != null)
        actor.getMonitor().addRestart();
    final Strand strand;
    if (actor.getStrand() != null)
        strand = actor.getStrand();
    else
        strand = createStrandForActor(child.actor != null && isLocal(child.actor) ? LocalActor.getStrand(child.actor) : null, actor);
    try {
        strand.start();
    } catch (IllegalThreadStateException e) {
        log().info("Child {} has already been started.", actor);
    }
    return start(child, actor.ref());
}
Also used : ActorRef(co.paralleluniverse.actors.ActorRef) LocalActor(co.paralleluniverse.actors.LocalActor) Actor(co.paralleluniverse.actors.Actor) Strand(co.paralleluniverse.strands.Strand)

Example 3 with Actor

use of co.paralleluniverse.actors.Actor in project quasar by puniverse.

the class RequestReplyHelper method call.

/**
 * Sends a request message to an actor, awaits a response value (but no longer than the given timeout) and returns it.
 * This method can be called by any code, even non-actor code.
 * If the actor responds with an error message, a {@link RuntimeException} will be thrown by this method.
 * <br>
 * The message's {@code id} and {@code from} properties may be left unset.
 * <p>
 * This method should be used as in the following example (assuming a {@code String} return value:</p>
 * <pre> {@code
 * String res = call(actor, new MyRequest());
 * }</pre>
 * In the example, {@code MyRequest} extends {@link RequestMessage}. Note how the result of the {@link #from() from} method is passed to the
 * request's constructor, but the message ID isn't.
 *
 * @param <V>     the return value's type
 * @param actor   the actor to which the request is sent
 * @param timeout the maximum duration to wait for a response
 * @param unit    the time unit of the timeout
 * @return the value sent by the actor as a response
 * @throws RuntimeException     if the actor responds with an error message, its contained exception will be thrown, possibly wrapped by a {@link RuntimeException}.
 * @throws TimeoutException     if the timeout expires before a response is received from the actor.
 * @throws InterruptedException
 */
public static <V> V call(final ActorRef actor, RequestMessage<V> m, long timeout, TimeUnit unit) throws TimeoutException, InterruptedException, SuspendExecution {
    assert !actor.equals(LocalActor.self()) : "Can't \"call\" self - deadlock guaranteed";
    if (m.getFrom() == null || LocalActor.isInstance(m.getFrom(), TempActor.class))
        m.setFrom(from());
    final boolean tmpActor = m.getFrom() instanceof TempActorRef;
    final Actor currentActor = tmpActor ? (Actor) ((TempActorRef) m.getFrom()).getImpl() : Actor.currentActor();
    assert currentActor != null;
    currentActor.link(actor);
    if (m.getId() == null)
        m.setId(new Object());
    final Object id = m.getId();
    final SelectiveReceiveHelper<Object> helper = new SelectiveReceiveHelper<Object>(currentActor) {

        @Override
        protected void handleLifecycleMessage(LifecycleMessage m) {
            if (m instanceof ExitMessage) {
                final ExitMessage exit = (ExitMessage) m;
                if (Objects.equals(exit.getActor(), actor) && exit.getWatch() == null)
                    throw Exceptions.rethrow(exit.getCause());
            }
            super.handleLifecycleMessage(m);
        }
    };
    try {
        actor.sendSync(m);
        final ResponseMessage response = (ResponseMessage) helper.receive(timeout, unit, new MessageProcessor<Object, Object>() {

            @Override
            public Object process(Object m) throws SuspendExecution, InterruptedException {
                return (m instanceof ResponseMessage && id.equals(((ResponseMessage) m).getId())) ? m : null;
            }
        });
        // no need to unlink in case of receiver death, so not done in finally block
        currentActor.unlink(actor);
        if (response instanceof ErrorResponseMessage)
            throw Exceptions.rethrow(((ErrorResponseMessage) response).getError());
        return ((ValueResponseMessage<V>) response).getValue();
    } catch (InterruptedException e) {
        if (tmpActor)
            currentActor.checkThrownIn();
        throw e;
    } finally {
    // if (tmpActor)
    // ((TempActor) m.getFrom()).done();
    }
}
Also used : SelectiveReceiveHelper(co.paralleluniverse.actors.SelectiveReceiveHelper) ExitMessage(co.paralleluniverse.actors.ExitMessage) MessageProcessor(co.paralleluniverse.actors.MessageProcessor) LocalActor(co.paralleluniverse.actors.LocalActor) Actor(co.paralleluniverse.actors.Actor) LifecycleMessage(co.paralleluniverse.actors.LifecycleMessage)

Example 4 with Actor

use of co.paralleluniverse.actors.Actor in project quasar by puniverse.

the class RequestReplyHelper method getCurrentActor.

private static ActorRef getCurrentActor() {
    ActorRef actorRef = LocalActor.self();
    if (actorRef == null) {
        // create a "dummy actor" on the current strand
        Actor actor = new TempActor();
        actorRef = actor.ref();
    }
    return actorRef;
}
Also used : ActorRef(co.paralleluniverse.actors.ActorRef) LocalActor(co.paralleluniverse.actors.LocalActor) Actor(co.paralleluniverse.actors.Actor)

Example 5 with Actor

use of co.paralleluniverse.actors.Actor in project quasar by puniverse.

the class SupervisorActor method addChild.

/**
 * Adds a new child actor to the supervisor. If the child has not been started, it will be started by the supervisor.
 *
 * @param spec the {@link ChildSpec child's spec}.
 * @return the actor (possibly after it has been started by the supervisor).
 * @throws InterruptedException
 */
protected final <T extends ActorRef<M>, M> T addChild(ChildSpec spec) throws SuspendExecution, InterruptedException {
    verifyInActor();
    final ChildEntry child = addChild1(spec);
    ActorRef<?> actor = null;
    if (spec.builder instanceof Actor) {
        final Actor a = ((Actor) spec.builder);
        actor = a.isStarted() ? a.ref() : a.spawn();
    }
    if (actor == null)
        actor = start(child);
    else
        start(child, actor);
    return (T) actor;
}
Also used : LocalActor(co.paralleluniverse.actors.LocalActor) Actor(co.paralleluniverse.actors.Actor)

Aggregations

Actor (co.paralleluniverse.actors.Actor)6 LocalActor (co.paralleluniverse.actors.LocalActor)5 ActorRef (co.paralleluniverse.actors.ActorRef)3 BasicActor (co.paralleluniverse.actors.BasicActor)1 ExitMessage (co.paralleluniverse.actors.ExitMessage)1 LifecycleMessage (co.paralleluniverse.actors.LifecycleMessage)1 MailboxConfig (co.paralleluniverse.actors.MailboxConfig)1 MessageProcessor (co.paralleluniverse.actors.MessageProcessor)1 SelectiveReceiveHelper (co.paralleluniverse.actors.SelectiveReceiveHelper)1 AbstractServerHandler (co.paralleluniverse.actors.behaviors.AbstractServerHandler)1 EventHandler (co.paralleluniverse.actors.behaviors.EventHandler)1 EventSource (co.paralleluniverse.actors.behaviors.EventSource)1 EventSourceActor (co.paralleluniverse.actors.behaviors.EventSourceActor)1 Initializer (co.paralleluniverse.actors.behaviors.Initializer)1 Server (co.paralleluniverse.actors.behaviors.Server)1 ServerActor (co.paralleluniverse.actors.behaviors.ServerActor)1 SuspendExecution (co.paralleluniverse.fibers.SuspendExecution)1 Store (co.paralleluniverse.galaxy.Store)1 StoreTransaction (co.paralleluniverse.galaxy.StoreTransaction)1 TimeoutException (co.paralleluniverse.galaxy.TimeoutException)1