Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the better method? Allowing the thread to sleep for a while or deleting it and recreating it later?

We have a process that needs to run every two hours. It's a process that needs to run on it's own thread so as to not interrupt normal processing.

When it runs, it will download 100k records and verify them against a database. The framework to run this has a lot of objects managing this process. These objects only need to be around when the process is running.

What's a better standard?

  1. Keep the thread in wait mode by letting it sleep until I need it again. Or,

  2. Delete it when it is done and create it the next time I need it? (System Timer Events.)

like image 936
Jeremiah Avatar asked Dec 04 '08 15:12

Jeremiah


3 Answers

There is not that much difference between the two solutions. I tend to prefer the one where the thread is created each time.

Having a thread lying around consumes resources (memory at least). In a garbage collected language, it may be easy to have some object retained in this thread, thus using even more memory. If you have not the thread laying around, all resources are freed and made available for two hours to the main process.

When you want to stop your whole process, where your thread may be executing or not, you need to interrupt the thread cleanly. It is always difficult to interrupt a thread or knowing if it is sleeping or working. You may have some race conditions there. Having the thread started on demand relieves you from those potential problems: you know if you started the thread and in that case calling thread_join makes you wait until the thread is done.

For those reasons, I would go for the thread on demand solution, even though the other one has no insurmontable problems.

like image 99
Pierre Avatar answered Oct 20 '22 20:10

Pierre


Starting one thread every two hours is very cheap, so I would go with that.

However, if there is a chance that at some time in the future the processing could take more than the run interval, you probably want to keep the thread alive. That way, you won't be creating a second thread that will start processing the records while the first is still running, possibly corrupting data or processing records twice.

like image 33
Rob Prouse Avatar answered Oct 20 '22 20:10

Rob Prouse


Either should be fine but I would lean towards keeping the thread around for cases where the verification takes longer than expected (ex: slow network links or slow database response).

like image 37
rich Avatar answered Oct 20 '22 20:10

rich