0

I have a thread cleaner in my code that is being created if the DB capacity was exceeded, the capacity is checked on every insertion to the DB. I would like to add more functionality to this cleaner and clean also when number of files exceeding, lets say 10000 files. The new functionality should run scheduled.

I want to be able to clean the DB in 2 ways:
1. On demand.
2. Scheduled, every day on X hour.

Which concurrent java class to use?
How can I make sure that the same thread will be used by the 2 ways above?

Snow
  • 339
  • 1
  • 5
  • 20

1 Answers1

3

Code that would perform cleanup of DB should be completely separated out of scheduling (single responsibility principle), so that you could execute it at any time from some other code.

As for scheduling, I would suggest you looking at Quartz scheduler, and get familiar with CRON so that you could extract it to properties to have possibility to change scheduling trigger without modifying your code.

You should synchronize your code so that no more than one cleanup gets performed at the same time, this should be easy with standard synchronize.

If you wish to make it very simple and don't want to add new dependencies, you can go with standard Java solution: Timer. Timer#scheduleAtFixedRate can provide fixed rate execution. Which means you'll have to add extra code whenever new requirements will show up (e.g., don't schedule at weekend).

Art Licis
  • 3,619
  • 1
  • 29
  • 49
  • Just to clarify, I have a thread cleaner in my code that is being created if the DB capacity was exceeded, the capacity is checked on every insertion to the DB. I would like to add more functionality to this cleaner and clean also when number of files exceeding, lets say 10000 files. The new functionality should run scheduled. – Snow Jul 16 '13 at 10:30
  • Well you can have different strategies to check for capacity exceed, nr of files exceed etc. And you can have mapping to appropriate cleanup strategy. Depending on your app load you may want e.g. to run it hourly on work days. I'm not sure if running on every insert is quite correct. And you can schedule each strategy separately, if they don't use shared resources. Or you can make it so two different cleanups don't run at the same time so that app wouldn't get high cpu. – Art Licis Jul 16 '13 at 10:39
  • Thanks Arturs you've been very helpful. – Snow Jul 16 '13 at 11:38