'Spring multi thread to update same table but different row
Currently, I am working on my personal Spring project on temperature data.
So basically there is an H2 database and a table containing different regions with the current temperature in that region.
And the temperature is fake data, just a random int generated within a random time range between 1-5 seconds. (Simulating the real world temperature are changing over time)
@Entity
@Transactional
@Table(name = "REGIONAL_WEATHER")
public class Weather {
@Id
@GeneratedValue
private int ID;
private String region;
private Integer temperature;
//getter setter constructor..
}
My question is I would like to try to update the table for each region in a faster way, so I designed to update it with multithreading, but I don't know am I doing it right, because some rows are not updated while the application is running... Serivce class:
@Service
public class WeatherService {
private WeatherRepository weatherRepository;
@Autowired
public WeatherService(WeatherRepository weatherRepository) {
this.weatherRepository = weatherRepository;
}
@Async
public CompletableFuture updateTemperature(String region)throws Exception{
double result = generateData(region);
return CompletableFuture.completedFuture(result);
}
public double generateData(String region) throws InterruptedException {
Random random = new Random();
Integer randomInt = random.nextInt(5) + 1;
Thread.sleep(randomInt * 1000);
Integer randomTemp = random.nextInt(40) + 10;
weatherRepository.updateTemp( region, randomTemp);
Optional<Weather> ow = weatherRepository.findTempByRegion("AAPL");
if (ow.isPresent()) {
return ow.get().getTemperature;
}
return 0.0;
}
}
And I use CommandRunner to run my thread:
@Component
public class AppRunner implements CommandLineRunner {
private final WeatherService weatherService;
@Autowired
public AppRunner(WeatherService weatherService) {
this.weatherService = weatherService;
}
@Override
public void run(String... args) throws Exception {
while(true){
CompletableFuture<Weather> page1 = weatherService.updateTemperature("USA");
CompletableFuture<Weather> page2 = weatherService.updateTemperature("UK");
CompletableFuture<Weather> page3 = weatherService.updateTemperature("CA");
CompletableFuture<Weather> page4 = weatherService.updateTemperature("JP");
page1.get();
page2.get();
page3.get();
page4.get();
}
}
}
It works but it is not working properly, because not all the rows are updating Only 2 out of 4 rows are updating. Can please someone tell me why and any good suggestions on it?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
