I am new to threads. I want to communicate with multiple sensors at one time after every minute continuously 24/7.
Senario:
I have a method to talk to the sensors which takes 3 arguments
public String perform(String command, String ip, String port)
{
//talk to the sensor and then
returns reply;
}
I have a database that contains the details of the sensor.
What I’m doing right now
while(true)
{
//get sensors from database
//run perform method for all instruments
for(int i=0;i<sensors.length-1;i++)
{
//call perform method and save the reply
}
Thread.sleep('one minute');
}
Problem:
The problem is if I have 100 sensors and each sensor takes 1 second to reply then after that I will be waiting for 1 minute, in this case I may lose some information. And to be honest sometime It takes more than a second to respond.
What I want to do is, get the information from the database for all the sensors
then create one thread for each sensor. Then run all the threads at one time which will return me some information. After that wait for one minute then do it again.
Any help is appreciated.
Thanks
Have you looked at the ScheduledThreadPoolExecutor ?
A simple usage would be to create a Callable for each of your sensors, and configure the thread pool to contain as many threads as you have sensors. Then submit each Callable, specifying an appropriate schedule.
Note that this approach doesn’t guarantee particularly accurate timings (Java’s not by any means a real-time platform). The other issue is that creating a lot of threads can be relatively memory-hungry (IIRC the standard heap allocation per thread is 512k, but it’s configurable) and this approach wouldn’t scale if you had 1000s of sensors.