Search in sources :

Example 11 with Scheduler

use of rx.Scheduler in project scalecube by scalecube.

the class FailureDetectorImpl method doPingReq.

private void doPingReq(final Member pingMember, String cid) {
    final int timeout = config.getPingInterval() - config.getPingTimeout();
    if (timeout <= 0) {
        LOGGER.trace("No PingReq[{}] occurred, because no time left (pingInterval={}, pingTimeout={})", period, config.getPingInterval(), config.getPingTimeout());
        publishPingResult(pingMember, MemberStatus.SUSPECT);
        return;
    }
    final List<Member> pingReqMembers = selectPingReqMembers(pingMember);
    if (pingReqMembers.isEmpty()) {
        LOGGER.trace("No PingReq[{}] occurred, because member selection is empty", period);
        publishPingResult(pingMember, MemberStatus.SUSPECT);
        return;
    }
    Member localMember = membership.member();
    transport.listen().observeOn(scheduler).filter(this::isPingAck).filter(message -> cid.equals(message.correlationId())).take(1).timeout(timeout, TimeUnit.MILLISECONDS, scheduler).subscribe(message -> {
        LOGGER.trace("Received transit PingAck[{}] from {} to {}", period, message.sender(), pingMember);
        publishPingResult(pingMember, MemberStatus.ALIVE);
    }, throwable -> {
        LOGGER.trace("Timeout getting transit PingAck[{}] from {} to {} within {} ms", period, pingReqMembers, pingMember, timeout);
        publishPingResult(pingMember, MemberStatus.SUSPECT);
    });
    PingData pingReqData = new PingData(localMember, pingMember);
    Message pingReqMsg = Message.withData(pingReqData).qualifier(PING_REQ).correlationId(cid).build();
    LOGGER.trace("Send PingReq[{}] to {} for {}", period, pingReqMembers, pingMember);
    for (Member pingReqMember : pingReqMembers) {
        transport.send(pingReqMember.address(), pingReqMsg);
    }
}
Also used : ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) ScheduledFuture(java.util.concurrent.ScheduledFuture) MembershipProtocol(io.scalecube.cluster.membership.MembershipProtocol) LoggerFactory(org.slf4j.LoggerFactory) MemberStatus(io.scalecube.cluster.membership.MemberStatus) Observable(rx.Observable) ArrayList(java.util.ArrayList) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Schedulers(rx.schedulers.Schedulers) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Transport(io.scalecube.transport.Transport) Message(io.scalecube.transport.Message) Subscribers(rx.observers.Subscribers) Logger(org.slf4j.Logger) Subscriber(rx.Subscriber) Scheduler(rx.Scheduler) Subject(rx.subjects.Subject) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Member(io.scalecube.cluster.Member) MembershipEvent(io.scalecube.cluster.membership.MembershipEvent) PublishSubject(rx.subjects.PublishSubject) Collections(java.util.Collections) Message(io.scalecube.transport.Message) Member(io.scalecube.cluster.Member)

Example 12 with Scheduler

use of rx.Scheduler in project scalecube by scalecube.

the class MembershipProtocolImpl method start.

/**
 * Starts running cluster membership protocol. After started it begins to receive and send cluster membership messages
 */
public CompletableFuture<Void> start() {
    // Init membership table with local member record
    Member member = memberRef.get();
    MembershipRecord localMemberRecord = new MembershipRecord(member, ALIVE, 0);
    membershipTable.put(member.id(), localMemberRecord);
    // Listen to incoming SYNC requests from other members
    onSyncRequestSubscriber = Subscribers.create(this::onSync, this::onError);
    transport.listen().observeOn(scheduler).filter(msg -> SYNC.equals(msg.qualifier())).filter(this::checkSyncGroup).subscribe(onSyncRequestSubscriber);
    // Listen to incoming SYNC ACK responses from other members
    onSyncAckResponseSubscriber = Subscribers.create(this::onSyncAck, this::onError);
    transport.listen().observeOn(scheduler).filter(msg -> SYNC_ACK.equals(msg.qualifier())).filter(// filter out initial sync
    msg -> msg.correlationId() == null).filter(this::checkSyncGroup).subscribe(onSyncAckResponseSubscriber);
    // Listen to events from failure detector
    onFdEventSubscriber = Subscribers.create(this::onFailureDetectorEvent, this::onError);
    failureDetector.listen().observeOn(scheduler).subscribe(onFdEventSubscriber);
    // Listen to membership gossips
    onGossipRequestSubscriber = Subscribers.create(this::onMembershipGossip, this::onError);
    gossipProtocol.listen().observeOn(scheduler).filter(msg -> MEMBERSHIP_GOSSIP.equals(msg.qualifier())).subscribe(onGossipRequestSubscriber);
    // Make initial sync with all seed members
    return doInitialSync();
}
Also used : ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) FailureDetector(io.scalecube.cluster.fdetector.FailureDetector) ScheduledFuture(java.util.concurrent.ScheduledFuture) Address(io.scalecube.transport.Address) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Observable(rx.Observable) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ImmutableList(com.google.common.collect.ImmutableList) Map(java.util.Map) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Schedulers(rx.schedulers.Schedulers) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Transport(io.scalecube.transport.Transport) Message(io.scalecube.transport.Message) Subscribers(rx.observers.Subscribers) ClusterMath(io.scalecube.cluster.ClusterMath) GossipProtocol(io.scalecube.cluster.gossip.GossipProtocol) Logger(org.slf4j.Logger) Subscriber(rx.Subscriber) Collection(java.util.Collection) Set(java.util.Set) FailureDetectorEvent(io.scalecube.cluster.fdetector.FailureDetectorEvent) Scheduler(rx.Scheduler) DEAD(io.scalecube.cluster.membership.MemberStatus.DEAD) Subject(rx.subjects.Subject) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) ALIVE(io.scalecube.cluster.membership.MemberStatus.ALIVE) Member(io.scalecube.cluster.Member) Preconditions(com.google.common.base.Preconditions) PublishSubject(rx.subjects.PublishSubject) Collections(java.util.Collections) Member(io.scalecube.cluster.Member)

Example 13 with Scheduler

use of rx.Scheduler in project AnDevCon-RxPatterns by colintheshots.

the class Example16Test method test_anomalous_network_event.

@Test
public void test_anomalous_network_event() {
    // TestScheduler lets you advance time by hand
    TestScheduler scheduler = Schedulers.test();
    TestSubscriber<NetworkResponse> subscriber = new TestSubscriber<>();
    // Scheduler.Worker lets you schedule events in time
    Scheduler.Worker worker = scheduler.createWorker();
    // Subjects allow both input and output, so they can be swapped in for
    // Retrofit calls to unit test your code.
    final PublishSubject<NetworkResponse> networkSubject = PublishSubject.create();
    // schedule a first observable event to occur at 1000 ms
    worker.schedule(new Action0() {

        @Override
        public void call() {
            networkSubject.onError(new TimeoutException());
        }
    }, 10000, TimeUnit.MILLISECONDS);
    // subscribing so events appear
    networkSubject.subscribeOn(scheduler).subscribe(subscriber);
    scheduler.advanceTimeBy(20000, TimeUnit.MILLISECONDS);
    subscriber.awaitTerminalEvent();
    // we use the class-based assertError method, since it's easier to match
    subscriber.assertError(TimeoutException.class);
    subscriber.assertValueCount(0);
    subscriber.assertUnsubscribed();
}
Also used : Action0(rx.functions.Action0) TestScheduler(rx.schedulers.TestScheduler) Scheduler(rx.Scheduler) TestSubscriber(rx.observers.TestSubscriber) TestScheduler(rx.schedulers.TestScheduler) Override(java.lang.Override) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test)

Example 14 with Scheduler

use of rx.Scheduler in project Hystrix by Netflix.

the class HystrixContextSchedulerTest method testUnsubscribeWrappedScheduler.

@Test(timeout = 2500)
public void testUnsubscribeWrappedScheduler() throws InterruptedException {
    Scheduler s = Schedulers.newThread();
    final AtomicBoolean interrupted = new AtomicBoolean();
    final CountDownLatch start = new CountDownLatch(1);
    final CountDownLatch end = new CountDownLatch(1);
    HystrixContextScheduler hcs = new HystrixContextScheduler(s);
    Scheduler.Worker w = hcs.createWorker();
    try {
        w.schedule(new Action0() {

            @Override
            public void call() {
                start.countDown();
                try {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException ex) {
                        interrupted.set(true);
                    }
                } finally {
                    end.countDown();
                }
            }
        });
        start.await();
        w.unsubscribe();
        end.await();
        assertTrue(interrupted.get());
    } finally {
        w.unsubscribe();
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Action0(rx.functions.Action0) Scheduler(rx.Scheduler) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 15 with Scheduler

use of rx.Scheduler in project vertx-examples by vert-x3.

the class Scheduled method start.

@Override
public void start() throws Exception {
    Observable<String> o = Observable.just("someID1", "someID2", "someID3", "someID4");
    // This scheduler can execute blocking actions
    Scheduler scheduler = io.vertx.rxjava.core.RxHelper.blockingScheduler(vertx);
    // All operations done on the observer now can be blocking
    o = o.observeOn(scheduler);
    // Load from a blocking api
    o = o.map(id -> blockingLoad(id));
    o.subscribe(item -> {
        System.out.println("Got item " + item);
    }, err -> {
        err.printStackTrace();
    }, () -> {
        System.out.println("Done");
    });
}
Also used : Scheduler(rx.Scheduler) Runner(io.vertx.example.util.Runner) AbstractVerticle(io.vertx.rxjava.core.AbstractVerticle) Observable(rx.Observable) Scheduler(rx.Scheduler)

Aggregations

Scheduler (rx.Scheduler)27 Test (org.junit.Test)13 TestScheduler (rx.schedulers.TestScheduler)9 Observable (rx.Observable)7 Schedulers (rx.schedulers.Schedulers)7 Executors (java.util.concurrent.Executors)6 ArrayList (java.util.ArrayList)5 List (java.util.List)5 Logger (org.slf4j.Logger)5 ThreadFactoryBuilder (com.google.common.util.concurrent.ThreadFactoryBuilder)4 Member (io.scalecube.cluster.Member)4 Message (io.scalecube.transport.Message)4 Transport (io.scalecube.transport.Transport)4 Collections (java.util.Collections)4 ExecutorService (java.util.concurrent.ExecutorService)4 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)4 TimeUnit (java.util.concurrent.TimeUnit)4 LoggerFactory (org.slf4j.LoggerFactory)4 Collection (java.util.Collection)3 ScheduledFuture (java.util.concurrent.ScheduledFuture)3