Working on an application right now that runs from the command line but will be a GUI in the future. It will connect to a sensor (probably for weeks at time) and gather information, I have 5 tasks that may run once a minute, every 5 minutes or at greater intervals depending on a user's preference. The tasks, would get the current sensor data and push to a web site, or ftp, or push to a database.
It looks like threads is the right solution but I wonder if java.util.Timer would work as well. There might be times where the tasks need to run at 5 minutes on clock so 5, 10, 15, etc. and I thought Timer would be good for this but I could not tell if I could share a data object with the timer task.
Also, I am guessing there would be overhead to the startup of each of these tasks each time using Timer and went back to the Thread approach.
So I am looking for guidance on approach and hope I have provided enough information to help a Greenhorn along.
Thanks for the responses. Is there a way to pass a data object to the Timer when it kicks off the way you share data with a Thread? The basic research I have done does not show that or I miss understood the examples.
Thanks for the push. I should have thought of that. Now I am off to build a test case.
Joined: Sep 19, 2009
I built a test case last night (actually borrowed some code examples) and found that with timer the task basically takes control from the main part of the program.
So in one case, I am concerned where I am making a telnet connection sending some data and closing but the time it takes is 23 seconds which is very long and would cause sensor data to be lost. The interface with telnet is mostly waiting for a response from the server and I have no control over that interface. So would threads improve this or would I have the same issue. I am making a basic assumption that threads would run in parallel and thought Timer tasks would run the same way.
A java.util.Timer only has one thread. So, you are have long running tasks, instead of short (either repeating or not) running tasks, they will be waiting for their turn.
If your task is really long running, it may be worth it to give it a dedicated thread... Also, if you want a Timer with multiple threads, aka. thread pools, take a look at the java.util.concurrent.Executors class instead.
Joined: Sep 19, 2009
I started playing with a simulated set of threads with one or two that are long running, one just constant one, and a couple of shorter ones. That seems to spread the load out a bit, now to put it into a real world scenario. It will be interesting to see what it does to the CPU use, I think I'll see some peak usage at certain times but that would be normal. I am gong to take a look at java.util.concurrent.Executors class to set this up as well.