Search in sources :

Example 6 with Func0

use of rx.functions.Func0 in project mosby by sockeqwe.

the class MailProvider method addMailWithDelay.

/**
   * Creates and saves a new mail
   */
public Observable<Mail> addMailWithDelay(final Mail mail) {
    return Observable.defer(new Func0<Observable<Mail>>() {

        @Override
        public Observable<Mail> call() {
            delay();
            Observable o = checkExceptions();
            if (o != null) {
                return o;
            }
            return Observable.just(mail);
        }
    }).flatMap(new Func1<Mail, Observable<Mail>>() {

        @Override
        public Observable<Mail> call(Mail mail) {
            return addMail(mail);
        }
    });
}
Also used : Func0(rx.functions.Func0) Observable(rx.Observable)

Example 7 with Func0

use of rx.functions.Func0 in project Hystrix by Netflix.

the class AbstractCommand method executeCommandWithSpecifiedIsolation.

private Observable<R> executeCommandWithSpecifiedIsolation(final AbstractCommand<R> _cmd) {
    if (properties.executionIsolationStrategy().get() == ExecutionIsolationStrategy.THREAD) {
        // mark that we are executing in a thread (even if we end up being rejected we still were a THREAD execution and not SEMAPHORE)
        return Observable.defer(new Func0<Observable<R>>() {

            @Override
            public Observable<R> call() {
                executionResult = executionResult.setExecutionOccurred();
                if (!commandState.compareAndSet(CommandState.OBSERVABLE_CHAIN_CREATED, CommandState.USER_CODE_EXECUTED)) {
                    return Observable.error(new IllegalStateException("execution attempted while in state : " + commandState.get().name()));
                }
                metrics.markCommandStart(commandKey, threadPoolKey, ExecutionIsolationStrategy.THREAD);
                if (isCommandTimedOut.get() == TimedOutStatus.TIMED_OUT) {
                    // and not increment any of the counters below or other such logic
                    return Observable.error(new RuntimeException("timed out before executing run()"));
                }
                if (threadState.compareAndSet(ThreadState.NOT_USING_THREAD, ThreadState.STARTED)) {
                    //we have not been unsubscribed, so should proceed
                    HystrixCounters.incrementGlobalConcurrentThreads();
                    threadPool.markThreadExecution();
                    // store the command that is being run
                    endCurrentThreadExecutingCommand = Hystrix.startCurrentThreadExecutingCommand(getCommandKey());
                    executionResult = executionResult.setExecutedInThread();
                    /**
                         * If any of these hooks throw an exception, then it appears as if the actual execution threw an error
                         */
                    try {
                        executionHook.onThreadStart(_cmd);
                        executionHook.onRunStart(_cmd);
                        executionHook.onExecutionStart(_cmd);
                        return getUserExecutionObservable(_cmd);
                    } catch (Throwable ex) {
                        return Observable.error(ex);
                    }
                } else {
                    //command has already been unsubscribed, so return immediately
                    return Observable.error(new RuntimeException("unsubscribed before executing run()"));
                }
            }
        }).doOnTerminate(new Action0() {

            @Override
            public void call() {
                if (threadState.compareAndSet(ThreadState.STARTED, ThreadState.TERMINAL)) {
                    handleThreadEnd(_cmd);
                }
                if (threadState.compareAndSet(ThreadState.NOT_USING_THREAD, ThreadState.TERMINAL)) {
                //if it was never started and received terminal, then no need to clean up (I don't think this is possible)
                }
            //if it was unsubscribed, then other cleanup handled it
            }
        }).doOnUnsubscribe(new Action0() {

            @Override
            public void call() {
                if (threadState.compareAndSet(ThreadState.STARTED, ThreadState.UNSUBSCRIBED)) {
                    handleThreadEnd(_cmd);
                }
                if (threadState.compareAndSet(ThreadState.NOT_USING_THREAD, ThreadState.UNSUBSCRIBED)) {
                //if it was never started and was cancelled, then no need to clean up
                }
            //if it was terminal, then other cleanup handled it
            }
        }).subscribeOn(threadPool.getScheduler(new Func0<Boolean>() {

            @Override
            public Boolean call() {
                return properties.executionIsolationThreadInterruptOnTimeout().get() && _cmd.isCommandTimedOut.get() == TimedOutStatus.TIMED_OUT;
            }
        }));
    } else {
        return Observable.defer(new Func0<Observable<R>>() {

            @Override
            public Observable<R> call() {
                executionResult = executionResult.setExecutionOccurred();
                if (!commandState.compareAndSet(CommandState.OBSERVABLE_CHAIN_CREATED, CommandState.USER_CODE_EXECUTED)) {
                    return Observable.error(new IllegalStateException("execution attempted while in state : " + commandState.get().name()));
                }
                metrics.markCommandStart(commandKey, threadPoolKey, ExecutionIsolationStrategy.SEMAPHORE);
                // semaphore isolated
                // store the command that is being run
                endCurrentThreadExecutingCommand = Hystrix.startCurrentThreadExecutingCommand(getCommandKey());
                try {
                    executionHook.onRunStart(_cmd);
                    executionHook.onExecutionStart(_cmd);
                    //the getUserExecutionObservable method already wraps sync exceptions, so this shouldn't throw
                    return getUserExecutionObservable(_cmd);
                } catch (Throwable ex) {
                    //If the above hooks throw, then use that as the result of the run method
                    return Observable.error(ex);
                }
            }
        });
    }
}
Also used : Action0(rx.functions.Action0) HystrixRuntimeException(com.netflix.hystrix.exception.HystrixRuntimeException) Func0(rx.functions.Func0) Observable(rx.Observable)

Example 8 with Func0

use of rx.functions.Func0 in project Hystrix by Netflix.

the class HystrixObservableCommandTest method testEarlyUnsubscribeDuringExecutionViaObserve.

@Test
public void testEarlyUnsubscribeDuringExecutionViaObserve() {
    class AsyncCommand extends HystrixObservableCommand<Boolean> {

        public AsyncCommand() {
            super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ASYNC")));
        }

        @Override
        protected Observable<Boolean> construct() {
            return Observable.defer(new Func0<Observable<Boolean>>() {

                @Override
                public Observable<Boolean> call() {
                    try {
                        Thread.sleep(100);
                        return Observable.just(true);
                    } catch (InterruptedException ex) {
                        return Observable.error(ex);
                    }
                }
            }).subscribeOn(Schedulers.io());
        }
    }
    HystrixObservableCommand<Boolean> cmd = new AsyncCommand();
    final CountDownLatch latch = new CountDownLatch(1);
    Observable<Boolean> o = cmd.observe();
    Subscription s = o.doOnUnsubscribe(new Action0() {

        @Override
        public void call() {
            System.out.println("OnUnsubscribe");
            latch.countDown();
        }
    }).subscribe(new Subscriber<Boolean>() {

        @Override
        public void onCompleted() {
            System.out.println("OnCompleted");
            latch.countDown();
        }

        @Override
        public void onError(Throwable e) {
            System.out.println("OnError : " + e);
        }

        @Override
        public void onNext(Boolean b) {
            System.out.println("OnNext : " + b);
        }
    });
    try {
        s.unsubscribe();
        assertTrue(latch.await(200, TimeUnit.MILLISECONDS));
        assertEquals("Number of execution semaphores in use", 0, cmd.getExecutionSemaphore().getNumberOfPermitsUsed());
        assertEquals("Number of fallback semaphores in use", 0, cmd.getFallbackSemaphore().getNumberOfPermitsUsed());
        assertFalse(cmd.isExecutionComplete());
        assertFalse(cmd.isExecutedInThread());
        System.out.println("EventCounts : " + cmd.getEventCounts());
        System.out.println("Execution Time : " + cmd.getExecutionTimeInMilliseconds());
        System.out.println("Is Successful : " + cmd.isSuccessfulExecution());
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
}
Also used : Action0(rx.functions.Action0) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Subscription(rx.Subscription) Func0(rx.functions.Func0) Test(org.junit.Test)

Example 9 with Func0

use of rx.functions.Func0 in project Hystrix by Netflix.

the class HystrixObservableCommandTest method testEarlyUnsubscribeDuringFallback.

@Test
public void testEarlyUnsubscribeDuringFallback() {
    class AsyncCommand extends HystrixObservableCommand<Boolean> {

        public AsyncCommand() {
            super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ASYNC")));
        }

        @Override
        protected Observable<Boolean> construct() {
            return Observable.error(new RuntimeException("construct failure"));
        }

        @Override
        protected Observable<Boolean> resumeWithFallback() {
            return Observable.defer(new Func0<Observable<Boolean>>() {

                @Override
                public Observable<Boolean> call() {
                    try {
                        Thread.sleep(100);
                        return Observable.just(false);
                    } catch (InterruptedException ex) {
                        return Observable.error(ex);
                    }
                }
            }).subscribeOn(Schedulers.io());
        }
    }
    HystrixObservableCommand<Boolean> cmd = new AsyncCommand();
    final CountDownLatch latch = new CountDownLatch(1);
    Observable<Boolean> o = cmd.toObservable();
    Subscription s = o.doOnUnsubscribe(new Action0() {

        @Override
        public void call() {
            System.out.println("OnUnsubscribe");
            latch.countDown();
        }
    }).subscribe(new Subscriber<Boolean>() {

        @Override
        public void onCompleted() {
            System.out.println("OnCompleted");
            latch.countDown();
        }

        @Override
        public void onError(Throwable e) {
            System.out.println("OnError : " + e);
        }

        @Override
        public void onNext(Boolean b) {
            System.out.println("OnNext : " + b);
        }
    });
    try {
        //give fallback a chance to fire
        Thread.sleep(10);
        s.unsubscribe();
        assertTrue(latch.await(200, TimeUnit.MILLISECONDS));
        assertEquals("Number of execution semaphores in use", 0, cmd.getExecutionSemaphore().getNumberOfPermitsUsed());
        assertEquals("Number of fallback semaphores in use", 0, cmd.getFallbackSemaphore().getNumberOfPermitsUsed());
        assertFalse(cmd.isExecutionComplete());
        assertFalse(cmd.isExecutedInThread());
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
}
Also used : Action0(rx.functions.Action0) CountDownLatch(java.util.concurrent.CountDownLatch) HystrixRuntimeException(com.netflix.hystrix.exception.HystrixRuntimeException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Subscription(rx.Subscription) Func0(rx.functions.Func0) Test(org.junit.Test)

Aggregations

Func0 (rx.functions.Func0)9 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)5 Observable (rx.Observable)5 Action0 (rx.functions.Action0)5 HystrixRuntimeException (com.netflix.hystrix.exception.HystrixRuntimeException)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 Test (org.junit.Test)4 Subscription (rx.Subscription)3 ArrayList (java.util.ArrayList)2 TestCircuitBreaker (com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker)1 HystrixContextScheduler (com.netflix.hystrix.strategy.concurrency.HystrixContextScheduler)1 List (java.util.List)1 Notification (rx.Notification)1 OnSubscribe (rx.Observable.OnSubscribe)1 Subscriber (rx.Subscriber)1 Action1 (rx.functions.Action1)1 Action2 (rx.functions.Action2)1 Func1 (rx.functions.Func1)1 TestSubscriber (rx.observers.TestSubscriber)1