Reputation: 354
So my application (spring-boot) runs really slow as it uses Selenium to scrape data, processes it and displays in the home page. I came across multithreading and I think it can be useful to my application to allow it to run faster, however the tutorials seem to display in the setting of a normal java application with a main. How can I multithread this single method in my controller?
The methods get.. are all selenium methods. I'm looking to run these 4 lines of code simultaneously
@Autowired
private WebScrape webscrape;
@RequestMapping(value = "/")
public String printTable(ModelMap model) {
model.addAttribute("alldata", webscrape.getAllData());
model.addAttribute("worldCases", webscrape.getWorlValues().get(0));
model.addAttribute("worldDeaths", webscrape.getWorlValues().get(1));
model.addAttribute("worldPop", webscrape.getWorlValues().get(2));
return "index";
}
Upvotes: 3
Views: 299
Reputation: 171
For every request to RequestMapping, a new thread will be created so what you want to achieve is already there. Please have a look:
https://www.oreilly.com/library/view/head-first-servlets/9780596516680/ch04s04.html
If you want to use multithreading anyway for other reason you can find the following useful:
@SpringBootApplication
@EnableAsync
public class ExampleSpringBootApp {
@Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(5);
executor.setQueueCapacity(25);
return executor;
}
public static void main(String[] args) {
//some code
}
}
This will create for you threadpool which you can feed with your tasks.
More information and guidelines:
https://spring.io/guides/gs/async-method/
Upvotes: 3