Search code examples
javamultithreadingjava-threads

call multiple methods simultaeously that returns returns object


Calling multiple methods and i want to call them simultaneously that should wait for one another to get completed.

else {
    PricingFromS4Request pricingRequest = new PricingFromS4Request();
    ProductFromS4Request productRequest = new ProductFromS4Request();
    PricingFromS4ServiceImpl service = new PricingFromS4ServiceImpl();

    //Create 1 thread for below line
    pricingRequest = service.createS4PricingRequest(ABeanObject, SomeArrayList);

    //Create 1 more thread for below line
    productRequest = service.createS4ProductRequest(SomeList);

    //Send pricingRequest and productRequest  into another method 
    SomeMethod(pricingRequest,productRequest);

}

Unable to put the two lines inside the thread


Solution

  • In Java 7 this would an option:

        PricingFromS4Request pricingRequest = new PricingFromS4Request();
        ProductFromS4Request productRequest = new ProductFromS4Request();
        PricingFromS4ServiceImpl service = new PricingFromS4ServiceImpl();
    
        ExecutorService executor = Executors.newFixedThreadPool(2);
    
        Future<PricingFromS4Request> f1 = executor.submit(new Callable<PricingFromS4Request >() {
            public PricingFromS4Request  call() {
                return service.createS4PricingRequest(ABeanObject, SomeArrayList);
            }
        });
        Future<ProductFromS4Request> f2 = executor.submit(new Callable<ProductFromS4Request>() {
            public ProductFromS4Request call() {
                return service.createS4ProductRequest(SomeList);
            }
        });
        SomeMethod(f1.get(), f2.get());
        executor.shutdown();