genxgeek
genxgeek

Reputation: 13347

Sending asynch/await .NET 4.5 like httpRequests in Java?

Is there a java equivalent of the following asynch/await .NET 4.5 code to handle httprequests or really any invoked method call)?

public async Task<System.IO.TextReader> DoRequestAsync(string url)
{
    HttpWebRequest req = HttpWebRequest.CreateHttp(url);
    req.AllowReadStreamBuffering = true;
    var tr = await DoRequestAsync(req);  // <- Wait here and even do some work if you want.
    doWorkWhilewaiting();                // ...look ma' no callbacks.
    return tr;
}

I was planning on calling this within a controller /GET method (to get data from 3rd partyl REST endpoint) and I'm completely new to the java world.

Any information is greatly appreciated.

Upvotes: 0

Views: 124

Answers (2)

vipcxj
vipcxj

Reputation: 1038

I released a apt library JAsync recently. It implements Async-Await pattern just like es in Java. And it use Reactor as its low level implementation. It is in alpha stage now. With it we can write code like that:

@RestController
@RequestMapping("/employees")
public class MyRestController {
    @Inject
    private EmployeeRepository employeeRepository;
    @Inject
    private SalaryRepository salaryRepository;

    // The standard JAsync async method must be annotated with the Async annotation, and return a JPromise object.
    @Async()
    private JPromise<Double> _getEmployeeTotalSalaryByDepartment(String department) {
        double money = 0.0;
        // A Mono object can be transformed to the JPromise object. So we get a Mono object first.
        Mono<List<Employee>> empsMono = employeeRepository.findEmployeeByDepartment(department);
        // Transformed the Mono object to the JPromise object.
        JPromise<List<Employee>> empsPromise = Promises.from(empsMono);
        // Use await just like es and c# to get the value of the JPromise without blocking the current thread.
        for (Employee employee : empsPromise.await()) {
            // The method findSalaryByEmployee also return a Mono object. We transform it to the JPromise just like above. And then await to get the result.
            Salary salary = Promises.from(salaryRepository.findSalaryByEmployee(employee.id)).await();
            money += salary.total;
        }
        // The async method must return a JPromise object, so we use just method to wrap the result to a JPromise.
        return JAsync.just(money);
    }

    // This is a normal webflux method.
    @GetMapping("/{department}/salary")
    public Mono<Double> getEmployeeTotalSalaryByDepartment(@PathVariable String department) { 
        // Use unwrap method to transform the JPromise object back to the Mono object.
        return _getEmployeeTotalSalaryByDepartment(department).unwrap(Mono.class);
    }
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499760

No, Java doesn't have anything like async/await. The java.util.concurrent package contains various helpful classes around concurrency (for thread pools, producer/consumer queues etc) but really it's the language support in C# 5 that ties everything together... and that's just not present in Java yet.

It's not part of the plans for Java 8 either, as far as I can tell - although things like method literals and lambda expressions will at least make the explicit callback approach a lot simpler than it is in Java 7.

Upvotes: 3

Related Questions