title: Clean Up Thread/Background Thread or Process/Service In Java
body: <p>I have a java project which is packaged as a jar and run. The code interacts with 2 databases, a primary database and a secondary database. A table X exists in both primary and secondary DB with same structure.</p>
  
  <p>A java thread in code uses a linked blocking queue and to this queue every DML query that runs on table X in primary DB is added. The thread keeps checking if queue has a new DML query object added and executes the same on secondary DB.</p>
  
  <p>At end of the day the requirement is to delete all the rows in table X for a given day but before that we reconcile table X in both the databases and in case count of rows mismatch the missing rows are first inserted in secondary DB and then deleted from primary DB.</p>
  
  <p>Here i am facing 2 problems:</p>
  
  <p>First problem is, as the number of DML queries added to the queue increases, execution of these queries becomes slow.</p>
  
  <p>Secondly if the jar is stopped and again restarted, the DML queries that were added to the queue but were not yet executed are lost because the queue is in memory and as such those rows are never moved to secondary DB.</p>
  
  <p>What i am looking for is an approach were in i can design either a background service or an external service which keeps on running independent of whether the main jar is running or stopped and keeps on performing the job of replicating the DML queries from primary DB to secondary DB.   </p>