Search code examples
pythonjavanetwork-programmingio

What is the best and fastest way to execute this pattern of code in Java?


I have to migrate the following pattern of code to Java. I was wondering what is the best way to do it in Java either with any library or without:

async def call_external_service(user):  
    async with session.get(url, headers=headers) as response:  
    response = await response.json()  
    # extract some field from the response  
    country = response.json()['country']  
    print(country)

async def get_countries(users):  
    tasks = [asyncio.ensure_future(call_external_service(user)) for user in users]  
    await asyncio.gather(*tasks, return_exceptions=True)

users = list()  
with open("users.txt", "r") as f:  
    for line in f.readlines():  
    users.append(line.strip('\n'))

asyncio.run(get_countries(users))

Thanks


Solution

  • In Java 21 and later, with virtual threads, there is little need for complicated async/reactive programming. You can have millions of virtual threads running straightforward code.

    Java comes with HTTP client classes.

    Java has convenient try-with-resources syntax to automatically close resources such as ExecutorService.

    Collection < User > users = … ; // Fetch. 
    try
    (
        ExecutorService es = Executors.newVirtualThreadPerTaskExecutor() ;
    )
    {
        for ( User : user ) 
        { 
            es.submit( … some task object — `Runnable` or `Callable` … ) ;
        }
    }
    // Flow-of-control stops here (blocks) until all submitted tasks complete/fail. 
    

    If you want, all that code seen above could be placed inside a Runnable to be run as a task on another thread in another executor service.

    Search to learn more. These topics have been covered extensively on Stack Overflow.