Backend Handbook
Leapwise
  • 👋Introduction
  • Software Design Principles & Clean Code
    • Atomicity
    • Modularity
    • Hierarchy
    • Loose coupling
    • Asynchronous programming
  • Development Practices
    • JavaDocs
    • Technical Debt
    • Testing Guidelines
      • The Importance of Test Automation
      • The Testing Pyramid
        • Unit Tests
        • Integration Tests
        • End-to-End Tests
      • Mutation Testing
      • Contract Tests
        • REST Controller Contract testing
        • OpenAPI Contract testing
      • Testing Frameworks
        • JUnit 5
        • Testcontainers
        • Mockito
      • Writing Clean Tests - Best Practices
    • Common library
    • Generic CRUD
    • Update Facade
  • Development Tools & Environment
    • Monitoring
    • Performance tuning
    • Multi-tenancy & Configuration Management
    • Git practices
    • CI/CD
    • Maven
  • Project Management
    • Jira
    • Confluence documentation
    • SCRUM
    • Our ways of working
  • LIFE AT LEAPWISE
    • Introduction
    • Who are we?
    • What do we do?
    • Our values
    • Hiring process
      • Hiring: A Mid Frontend Developer's Point of View
    • Benefits we offer
    • Onboarding process
      • Onboarding: A Senior Digital Marketing Specialist's perspective
    • Mentorship program
    • Career development
      • Trainings & certificates we offer
      • Career development: A Senior Software Developer's Insight
    • Community building
    • Juniorship
    • First-hand info from our first team member
    • Join our team
Powered by GitBook
LogoLogo

Company

  • About
  • Culture
  • Services

Insights

  • Leapwise Newsletter
  • Blog

© Leapwise

On this page
  • How does asynchronous programming work?
  • Asynchronous programming vs. synchronous programming
  • Benefits of asynchronous programming
  • When to avoid asynchronous programming
  • Approaches for Asynchronous Programming

Was this helpful?

  1. Software Design Principles & Clean Code

Asynchronous programming

Asynchronous programming is a method of parallel computer programming that enables a process to run separately from the primary function of the program. Once the process completes, it communicates this information and may impact the primary function. Asynchronous programming often helps reduce or prevent wait times or lags in computer programming by enabling processes to continue to run in the background of the primary application.

How does asynchronous programming work?

When you use asynchronous programming, you create an event loop. This is a process that waits for and dispatches events or messages, called a promise, in a program. As part of the event loop, you may create a callback, which allows the event loop to supply information from the program to another piece of code, typically the primary function of the program.

During that time, the application can perform other tasks while you await the program. This allows potentially taxing tasks to run without forcing the user to wait for their completion. Await is a function or operation of many programming languages that allows asynchronous programming.

Asynchronous programming vs. synchronous programming

Both asynchronous and synchronous programming involve similar concepts within the broader field of computer programming. Synchronous or sequential programming is when tasks occur separately or one after another. The program pauses while the system performs the action and only responds once it receives the result. It features a single-thread model, meaning that it only performs a single action at a time.

Asynchronous programming differs in that it allows multiple tasks to run at the same time, and the programmer can often manage these tasks directly. It allows programs to continue to run even after you start a specific action.

Benefits of asynchronous programming

There are several benefits associated with asynchronous programming, including:

  • It provides an improved user experience. Asynchronous operations can improve the overall user experience since it helps systems run more efficiently. It helps reduce wait times, which often inconvenience customers.

  • It helps improve an application's performance. This type of programming can also help improve an application's speed, responsiveness and overall performance.

  • It's applicable in a broad range of programming languages. While asynchronous programming can make coding more complex, it's possible to apply the technique to a variety of languages with different syntaxes.

  • It can improve the speed of a program. Since asynchronous programming allows a program to run multiple processes at the same time, even though they may take different periods to function, it can help the program complete its processes faster.

  • It creates efficient memory management. Asynchronous programming can search for data in a memory set, such as a database, while performing other functions, making memory management faster for an application.

When to avoid asynchronous programming

While there are many positive uses for asynchronous programming, it's not always the best option. When executing code that calls for accessing and updating stored data, which multiple processes may access, asynchronous performance may not be the ideal option. Changing records in one process while another tries to access them can lead to inaccurate or corrupted data.

Approaches for Asynchronous Programming

There are two commonly used approaches for Asynchronous Programming as mentioned below:

  • Callbacks with CompletableFuture

  • Future and ExecutorService

Callbacks with CompletableFuture

The CompletableFuture is a class introduced in Java 8 that facilitates asynchronous programming using the callback-based approach. It represents a promise that may be asynchronously completed with the value or an exception. It provides various methods like supplyAsync, runAsync, and thenApplyAsync for asynchronous programming. We don’t need to use the ExecutorService explicitly. The CompletableFuture internally uses ForkJoinPool to handle the task asynchronously.

CompletableFuture
    .supplyAsync(new SomeService())
    .thenAccept(result -> System.out.println(result))
    .exceptionally(e -> { e.printStackTrace(); return null;})
    .thenRun(() -> System.out.println("Wrap-up!"));

Future and ExecutorService

The Future and ExecutorService can be used for the asynchronous programming in a more traditional way. The ExecutorService allows you to submit tasks for the asynchronous execution.

ExecutorService executor = Executors.newFixedThreadPool(THREADS_COUNT);

Callable<String> task = () -> {
    TimeUnit.MILLISECONDS.sleep(500);
    return "Task executed!";
};

Future<String> future = executor.submit(task);
PreviousLoose couplingNextJavaDocs

Last updated 12 months ago

Was this helpful?

Page cover image