Home How to work with CompletableFuture with SpringBoot for restful service
Reply: 0

How to work with CompletableFuture with SpringBoot for restful service

user45225
1#
user45225 Published in September 19, 2018, 11:13 am

I am facing trouble to understand how an async method works in SpringBoot.

Consider I am implementing a micro-service to get the Current, In-process or SoldOff Property of a user or All, depending on the query parameter from the user. I am calling two methods which calls sql scripts to give me the answer. I want to run those methods Asynchronously as it can take time.

Example:

@Service
public class PropertyService {

  public PropertyVO getPropertySummary() {

        CompletableFuture<List<Property>> currentProperty = null;
        CompletableFuture<List<Property>> soldProperty = null;
        CompletableFuture<List<Property>> inProcessProperty = null;

        CompletableFuture<List<Property>> allProperty = null;

        if(status.equals("ALL")) {

            allProperty = propertyDAO.getAllProperty(userId);

        }else {

            String[] statuses = status.split(",");

            for (String st : statuses) {

                if (st.equals("CURRENT")) {

                    currentProperty = propertyDAO.getCurrentProperty(userId);

                } else if (st.equals("SOLD")) {

                    soldProperty = propertyDAO.getSoldProperty(userId);

                } else if (st.equals("IN-Process")) {

                    inProcessProperty = propertyDAO.getInProcessProperty(userId);
                }
            }

            // Do I need this? How would it work when user just needs CURRENT and SOLD. Will it get stuck on IN-PROCESS?
            // CompletableFuture.allOf(currentProperty,soldProperty,inProcessProperty).join();
        }

        // Will it wait here for the above methods to run?
        List<Property> allPropertyList = getResult(allProperty);

        List<Property> currentPropertyList = getResult(currentProperty);
        List<Property> soldPropertyList = getResult(soldProperty);
        List<Property> inProcessPropertyList = getResult(inProcessProperty);

        ..... return Object Property
  }  


  private List<Property> getResult(final CompletableFuture<List<Property>> completableFuture) {

        if(completableFuture == null) {
            return Lists.newArrayList();
        }

        return completableFuture.get(30,TIMEUNIT.SEC);
    }

}  

@Repository
class PropertyRepository {

 @Async
 @Transactional(readOnly = true)
 public CompletableFuture<List<Property>> getCurrentProperty(int userId) {

     String query = sqlRetriever.getQueryByKey("SQL_GET_CURRENT_PROPERTY");

     return CompletableFuture.completedFuture(getNamedParameterJdbcTemplate().query(query,new PropertyMapper()));
}    


@SpringBootApplication
@EnableAsync
public class SpringBootApp {

    /**
     * The entry point into the application.
     *
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication.run(SpringBootApp.class, args).close();
    }

    @Bean
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(2);
        executor.setQueueCapacity(500);
        executor.setThreadNamePrefix("Property-");
        executor.initialize();
        return executor;
    }
}

Question:

  • Will this asynchronous call work?
  • Do I need to use the join method of CompletableFuture? It may happen that other CompletebleFuture instances can be null, if not
    provided through query parameter. for eg, User only provides CURRENT.
  • Do I need to mention @EnableAsync and asyncExecutor?

Any Help would be appreciated, I read through all the notes online but I am still confused a little. I cannot run it locally because i still do not have a full fledged code.

share|improve this question
  • Any idea how can I solve this issue ? – LifeStartsAtHelloWorld Apr 16 at 14:18

active oldest votes

Your Answer

StackExchange.ifUsing("editor", function () { StackExchange.using("externalEditor", function () { StackExchange.using("snippets", function () { StackExchange.snippets.init(); }); }); }, "code-snippets"); StackExchange.ready(function() { var channelOptions = { tags: "".split(" "), id: "1" }; initTagRenderer("".split(" "), "".split(" "), channelOptions); StackExchange.using("externalEditor", function() { // Have to fire editor after snippets, if snippets enabled if (StackExchange.settings.snippets.snippetsEnabled) { StackExchange.using("snippets", function() { createEditor(); }); } else { createEditor(); } }); function createEditor() { StackExchange.prepareEditor({ heartbeatType: 'answer', convertImagesToLinks: true, noModals: false, showLowRepImageUploadWarning: true, reputationToPostImages: 10, bindNavPrevention: true, postfix: "", onDemand: true, discardSelector: ".discard-answer" ,immediatelyShowMarkdownHelp:true }); } });
 
StackExchange.ready( function () { StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f49848366%2fhow-to-work-with-completablefuture-with-springboot-for-restful-service%23new-answer', 'question_page'); } );

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged java spring-boot asynchronous or ask your own question.

StackExchange.ready(function(){$.get('/posts/49848366/ivc/5671');});
StackExchange.ready(function () { StackExchange.responsiveness.addSwitcher(); }) (function(i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function() { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m); })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga'); StackExchange.ready(function () { StackExchange.ga.init({ sendTitles: true, tracker: window.ga, trackingCodes: [ 'UA-108242619-1' ] }); StackExchange.ga.setDimension('dimension2', '|java|spring-boot|asynchronous|'); StackExchange.ga.setDimension('dimension3', 'Questions/Show'); StackExchange.ga.trackPageView(); }); /**/ var _qevents = _qevents || [], _comscore = _comscore || []; (function() { var ssl = 'https:' == document.location.protocol, s = document.getElementsByTagName('script')[0], qc = document.createElement('script'); qc.async = true; qc.src = (ssl ? 'https://secure' : 'http://edge') + '.quantserve.com/quant.js'; s.parentNode.insertBefore(qc, s); _qevents.push({ qacct: "p-c1rF4kxgLUzNc" }); /**/ var sc = document.createElement('script'); sc.async = true; sc.src = (ssl ? 'https://sb' : 'http://b') + '.scorecardresearch.com/beacon.js'; s.parentNode.insertBefore(sc, s); _comscore.push({ c1: "2", c2: "17440561" }); })();
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.353045 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO