I need to read the data from a table every minute through thread & then perform certain action.
Should I just start a thread & put it in sleep mode for 1 minute
"Should I just start a thread & put it in sleep mode for 1 minute" Even if you want you want to go with traditional thread ( dont want to use executor Fremework) DO NOT USE SLEEP for waiting purpose as it will not release lock and its a blocking operation . DO USE wait(timeout) here.
Wrong Approach -
public synchronized void doSomething(long time) throws InterruptedException {
// ...
Thread.sleep(time);
}
Correct Approach
public synchronized void doSomething(long timeout) throws InterruptedException {
// ...
while (<condition does not hold>) {
wait(timeout); // Immediately releases the current monitor
}
}
you may want to check link https://www.securecoding.cert.org/confluence/display/java/LCK09-J.+Do+not+perform+operations+that+can+block+while+holding+a+lock
As so often, the Java 5 extensions from the java.util.concurrent package are a huge help here.
You should use the ScheduledThreadPoolExecutor. Here is a small (untestet) example:
class ToSomethingRunnable implements Runnable {
void run() {
// Add your customized code here to update the contents in the database.
}
}
ScheduledThreadPoolExecutor executor = Executors.newScheduledThreadPool(1);
ScheduledFuture<?> future = executor.scheduleAtFixedRate(new ToSomethingRunnable(),
0, 1, TimeUnit.MINUTES);
// at some point at the end
future.cancel();
executor.shutdown();
Update:
A benefit of using an Executor is you can add many repeating tasks of various intervals all sharing the same threadpool an the simple, but controlled shutdown.
An alternative to create a thread yourself is to use the ExcecutorService, where
Executors.newScheduledThreadPool( 1 )
creates a thred pool of size 1
and scheduleAtFixedRate
has the signature: scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);
public class ScheduledDBPoll
{
public static void main( String[] args )
{
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool( 1 );
ScheduledFuture<?> sf = scheduler.scheduleAtFixedRate(
new Runnable() {
public void run() {
pollDB();
}
},
1, 60,TimeUnit.SECONDS );
}
}
Your approach is good.You can proceed your approach.
This Sample will help you to do your task:
class SimpleThread extends Thread {
public SimpleThread(String str) {
super(str);
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
// Add your customized code here to update the contents in the database.
sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {}
}
System.out.println("DONE! " + getName());
}
}