Reputation: 2461
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
Upvotes: 0
Views: 497
Reputation: 5570
Personally I would take a different approach. I would have the server always listening via a RESTful API and then have the sensors POST their state every minute (or other interval you decide). This way the server and the sensors don't need to be within the same JVM and IMHO is more scalable. Also, this way any sensor can also query for the state of any other sensor via another RESTful API on the server.
Additionally the server can start a thread to handle each POST and if one sensor is taking very long, the others are not blocked.
Upvotes: 0
Reputation: 272347
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.
Upvotes: 2