1

My question is about this answer here that seems to work for my case (tomcat). However I see that it uses a newSingleThreadScheduledExecutor(). In my case the periodical task that has to be executed could be long lasting and I want to make sure that it will not block my web site until it has completed (run as a separated Thread). In addition I want to make sure that my task Runnable will be able to share mySQL connection pool (through hibernate) that the web site is using. So, is that still the correct approach or do I have to use something else?

Community
  • 1
  • 1
lviggiani
  • 5,824
  • 12
  • 56
  • 89
  • My solution to this would be to use a scheduler such as Quartz. It's easy to work with and has been tested in prod for years. However, I don't feel like writing this as an answer to the topic, since I'm generally against introducing new frameworks to solve a single task:) – Robin Jonsson Feb 16 '15 at 13:41

1 Answers1

2

I want to make sure that it will not block my web site until it has completed (run as a separated Thread)

The HTTP connector thread pool and the thread pool allocated to run timer tasks are different. They are not dependent on each other and will not block your website.

In addition I want to make sure that my task Runnable will be able to share mySQL connection pool (through hibernate) that the web site is using. So, is that still the correct approach or do I have to use something else?

Configure a common connection pool using a framework like commons DBCP and lookup the resource on the JNDI. Once you lookup that DataSource and the work on the connection has terminated, return the connection back to the pool.

The approach is fine.

Deepak Bala
  • 11,095
  • 2
  • 38
  • 49
  • Thank you very much. As for the connection, I'm already using jdbc + hibernate – lviggiani Feb 16 '15 at 14:18
  • one more question. Are all tasks added by " scheduler.scheduleAtFixedRate" executed sequentially (in a single thread) or are they executed in parallel and each task has its own Thread? I'm looking for a multi thread solution where each task is executed independently – lviggiani Feb 16 '15 at 14:28
  • Ok I made a test and saw that the "newSingleThreadScheduledExecutor" will execute the tasks sequentially. If I want to use them in parallel, then I need to use a "newScheduledThreadPool" – lviggiani Feb 16 '15 at 14:44
  • Check out the [ScheduledThreadPoolExecutor](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html) for concurrency. – Deepak Bala Feb 16 '15 at 14:45