DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • Mastering Concurrency: An In-Depth Guide to Java's ExecutorService
  • Overview of C# Async Programming
  • Designing Scalable Multi-Agent AI Systems: Leveraging Domain-Driven Design and Event Storming
  • How to Design Event Streams, Part 3

Trending

  • How to Format Articles for DZone
  • Threat Modeling for Developers: Identifying Security Risks in Software Projects
  • Maximizing Productivity: GitHub Copilot With Custom Instructions in VS Code
  • Top Tools for Front-End Developers

RxJava: Fixed-Rate vs. Fixed-Delay

This dip into scheduling with RxJava will clear up how and when to use a fixed rate or a fixed delay, with considerations made for both approaches.

By 
Tomasz Nurkiewicz user avatar
Tomasz Nurkiewicz
DZone Core CORE ·
Oct. 31, 17 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
14.8K Views

Join the DZone community and get the full member experience.

Join For Free

If you are using plain Java, since version 5, we have a handy scheduler class that allows running tasks at a fixed rate or with a fixed delay:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

ScheduledExecutorService scheduler = 
        Executors.newScheduledThreadPool(10);


Basically, it supports two types of operations:

scheduler.scheduleAtFixedRate(() -> doStuff(), 2, 1, SECONDS);

scheduler.scheduleWithFixedDelay(() -> doStuff(), 2, 1, SECONDS);


  • scheduleAtFixedRate() will make sure doStuff() is invoked precisely every second with an initial delay of two seconds. Of course, garbage collection, context-switching, etc. still can affect the precision. scheduleWithFixedDelay() is seemingly similar, but it takes doStuff() processing time into account. For example, if doStuff() runs for 200ms, fixed rate will wait only 800ms until next retry.

  • scheduleWithFixedDelay() on the other hand, always waits for the same amount of time (1 second in our case) between retries. Both behaviors are, of course, desirable under different circumstances. Remember that when doStuff() is slower than 1 second, scheduleAtFixedRate() will not preserve the desired frequency. Even though our ScheduledExecutorService has 10 threads, doStuff() will never be invoked concurrently to overlap with a previous execution. Therefore, in this case, the rate will actually be less than configured.

Scheduling in RxJava

Simulating scheduleAtFixedRate() with RxJava is very simple with the interval() operator... with a few caveats:

Flowable
        .interval(2, 1, SECONDS)
        .subscribe(i -> doStuff());


If doStuff() is slower than 1 second, bad things happen. First of all, we are using a default Schedulers.computation() thread pool inherited from the interval() operator. It's a bad idea. This thread pool should only be used for CPU-intensive tasks and is shared across all of RxJava. A better idea is to use your own scheduler (or at least io()):

Flowable
        .interval(2, 1, SECONDS)
        .observeOn(Schedulers.io())
        .subscribe(i -> doStuff());


observeOn() switches from the computation() scheduler used by interval() to the io() scheduler. Because the subscribe() method is never invoked concurrently by design, doStuff() is never invoked concurrently, just like with scheduleAtFixedRate(). However, the interval() operator tries very hard to keep a constant frequency. This means that if doStuff() is slower than 1 second, after a while, we should expect a MissingBackpressureException.

RxJava basically tells us that our subscriber is too slow, but interval() (by design) can't slow down. If you tolerate (or even expect) overlapping concurrent executions of doStuff(), it's very simple to fix. First, you must wrap the blocking doStuff() with the non-blocking Completable. Technically, Flowable Single or Maybe would work just as well, but since doStuff() is void, Completable sounds fine:

import io.reactivex.Completable;
import io.reactivex.schedulers.Schedulers;

Completable doStuffAsync() {
    return Completable
            .fromRunnable(this::doStuff)
            .subscribeOn(Schedulers.io())
            .doOnError(e -> log.error("Stuff failed", e))
            .onErrorComplete();
}


It's important to catch and swallow exceptions. Otherwise, a single error will cause the whole interval() to interrupt. doOnError() allows logging, but it passes the exception downstream. doOnComplete(), on the other hand, simply swallows the exception. We can now simply run this operation at each interval event:

Flowable
        .interval(2, 1, SECONDS)
        .flatMapCompletable(i -> doStuffAsync())
        .subscribe();


If you don't, the subscribe() loop will never start — but that's RxJava 101. Notice that if doStuffAsync() takes more than one second to complete, we will get overlapping, concurrent executions. There is nothing wrong with that, you just have to be aware of it. But what if what you really need is a fixed delay?

Fixed Delays in RxJava

In some cases, you need a fixed delay: Tasks should not overlap, and we should keep some breathing time between executions. No matter how slow a periodic task is, there should always be a constant time pause.

The interval() operator is not suitable to implement this requirement. However, it turns out the solution in RxJava is embarrassingly simple. Think about it: You need to sleep for a while, run some task, and when this task completes, repeat. Let me go over it again:

  • Sleep for a while (have some sort of a timer())
  • Run some task and wait for it to complete()
  • repeat()

That's it!

Flowable
        .timer(1, SECONDS)
        .flatMapCompletable(i -> doStuffAsync())
        .repeat()
        .subscribe();


The timer() operator emits a single event (0 of type Long) after a second. We use this event to trigger doStuffAsync(). When our stuff is done, the whole stream completes — but we would like to repeat!

Well, the repeat() operator does just that: When it receives a completion notification from upstream, it resubscribes. Resubscription basically means: wait 1 second more, fire doStuffAsync() — and so on.

Task (computing) job scheduling Thread pool Operator (extension) Execution (computing) IT Event Design Upstream (software development) Pass (software)

Published at DZone with permission of Tomasz Nurkiewicz, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Mastering Concurrency: An In-Depth Guide to Java's ExecutorService
  • Overview of C# Async Programming
  • Designing Scalable Multi-Agent AI Systems: Leveraging Domain-Driven Design and Event Storming
  • How to Design Event Streams, Part 3

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: