Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement custom asynchronous operation in Vert.x?

I am newbie in Vert.x.

For example, JDBCClient has non-blocking method

JDBCClient.getConnection(Handler<AsyncResult<SQLConnection>> handler)

When I call it, it is really asynchronous.

jdbcClient.getConnection(result -> { /* this code will execute asynchonous */})

But how can I implement my own component with non-blocking methods?

When I write for example this, it doesnt looks asynchronous. It just will execute method body and then will call passed lambda.

 class MyComponent { 
   public void getSomething(Handler<AsyncResult<String>> handler) {
       String result = someHeavyMethodInThisThread();
       handler.handle(Future.succeededFuture(result));
   }
 }
 /* later */

 /* this code will be blocking, right? */
 myComponent.getSomething(res -> { /* ... */ })

Maybe there is way to tell Vert.x that my method should be asynchronous? Some annotation or something else?

like image 668
Enbugger Avatar asked Nov 23 '17 17:11

Enbugger


People also ask

How asynchronous programming is implemented?

Asynchronous programming is a form of parallel programming that allows a unit of work to run separately from the primary application thread. When the work is complete, it notifies the main thread (as well as whether the work was completed or failed).

Is Vertx asynchronous?

Vertx-sync is a set of utilities that allow you to perform asynchronous operations and receive events in a synchronous way, but without blocking kernel threads.

Can we do asynchronous programming in Java?

Java SE 17 comes with its own asynchronous programming model. This course shows you how you can leverage this API to setup asynchronous systems, triggering tasks on the completion of other tasks, and how you report errors or recover from them.


1 Answers

There is nothing wrong with your code, your code style, normally will be async because the moment you perform a IO operation or call a vert.x API a async operation will detach you from the current thread (event loop).

In your case you're doing CPU bound code so it does not behave as async and as you stated will just call the lambda. If you want nevertheless make it async you can always wrap your code with runOnContext and that will enqueue it to be run on the next iteration of the event loop, e.g.:

class MyComponent { 
  public void getSomething(Handler<AsyncResult<String>> handler) {
    vertx.runOnContext(v -> {
      String result = someHeavyMethodInThisThread();
      handler.handle(Future.succeededFuture(result));
    });
  }
}
like image 136
Paulo Lopes Avatar answered Sep 30 '22 06:09

Paulo Lopes