How to initialise Thread to sleep - java

i am trying to write a method that pings my database every hour. In doing so I am having some difficulties in sleeping the Thread is it might not have been initialised
private void pingServer(){
final Thread serverPing = new Thread(new Runnable() {
#Override
public void run() {
Connection conn = null;
try {
conn = source.getConnection();
while(conn.isValid(3600)){
//no need to do anything as conn.isValid does the ping
serverPing.sleep(3600000);
}
} catch (SQLException | InterruptedException e) {}
finally{
closeConnection(conn);
}
}
});
serverPing.setDaemon(true);
serverPing.start();
}
How can i modify this code to initialise it correctly?
Thanks

To sleep, just use Thread.sleep(3600000);
Yet, you should use a ScheduledExecutorService for this kind of tasks:
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
try(Connection conn = source.getConnection()){
if(!conn.isValid(3600)){
// do something if the connection is invalid
}
}
}
}, 0, 1, TimeUnit.HOURS);

Just use Thread.sleep(TIME_GAP); to sleep the current thread.
Example
while(conn.isValid(3600)){
try {
Thread.sleep(3600000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

Related

Stop thread execution when it calls url.openStream() in a loop

Edit: I know what Thread.interrupt() does.
while (!Thread.currentThread().isInterrupted()) does not exit when I interrupt the thread.
I also tried to catch an exception from url.openStream(); when the
thread is interrupted (desperation, maybe it was a blocking method,
which is not) and exit the loop, without any success.
The application creates a Thread that continuously reads a URL. After 3 seconds that Thread gets interrupted but unfortunately continues to execute.
How to stop the thread from executing?
Code (Main.java, MyRunnable.java):
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable("http://ninjaflex.com/");
Thread thread = new Thread(runnable);
thread.start();
sleep(3000);
thread.interrupt();
System.out.println("Thread.interrupt() invoked.");
}
private static void sleep(long timeMilli) {
try {
Thread.sleep(timeMilli);
} catch (Exception e) {
}
}
}
public class MyRunnable implements Runnable {
private String website;
MyRunnable(String website) {
this.website = website;
}
#Override
public void run() {
URL url = createUrl();
if (url != null) {
while (!Thread.currentThread().isInterrupted()) {
sleepOneSec();
readFromUrl(url);
System.out.println("Read from " + website);
}
System.out.println("Script: Interrupted, exiting.");
}
}
private URL createUrl() {
URL url = null;
try {
url = new URL(website);
} catch (MalformedURLException e) {
System.out.println("Wrong URL?");
}
return url;
}
private void sleepOneSec() {
try {
Thread.sleep(1000);
} catch (Exception e) {
System.out.println("Error sleeping");
}
}
private void readFromUrl(URL url) {
InputStream in = null;
try {
in = url.openStream();
} catch (Exception e) {
System.out.println("Exception while url.openStream().");
e.printStackTrace();
} finally {
closeInputStream(in);
}
}
private void closeInputStream(InputStream in) {
try {
in.close();
} catch (IOException e) {
System.out.println("Error while closing the input stream.");
}
}
}
Basically, your MyRunnable thread is interrupted during sleep. InterreuptedException is thrown but catched. By the way, it's a bad habit to catch Exception and you should not do that.
From the javadoc: "The interrupted status of the current thread is cleared when this exception is thrown".
Therefore, your while loop will never see the flag.
Replace the call to the sleepOneSec method with a simple Thread.sleep call. Catch InterruptedException outside your while loop. This will cause the loop to exit naturally:
try {
while (true) {
Thread.sleep(1000);
readFromUrl(url);
System.out.println("Read from " + website);
}
} catch (InterruptedException e) {
System.out.println("Script: Interrupted, exiting.");
}
I removed the MyRunnable.sleepOneSec and your code started to work.

java.util.concurrent.ScheduledExecutorService: is it possible to wait for a service to finish before starting another one?

I set 2 services in my web.xml and I create for each a shedule service as this:
public class MyScheduler implements ServletContextListener {
private ScheduledExecutorService scheduledExecutorService = null;
#Override
public void contextInitialized(ServletContextEvent sce) {
if ((scheduledExecutorService == null) || (!scheduledExecutorService.isTerminated())) {
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.scheduleAtFixedRate(new MyScheduledTimer(), 0, 15, TimeUnit.DAYS);
}
}
#Override
public void contextDestroyed(ServletContextEvent sce) {
try {
scheduledExecutorService.shutdown();
} catch (Exception ex) {
}
}
}
class MyScheduledTimer extends TimerTask {
{
try {
MyEjb ejbObject = (InterfaceEjb) new InitialContext().lookup("java:global/project/MyEjb");
} catch (NamingException ex) {
Logger.getLogger(MyScheduler.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(MyScheduler.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void run() {
//my code to run with ejbObject...
}
}
I would like to run first service to startup my application, waiting that this service is completed and after run the second service. Is it possibile?
If you want to use something more specific - you can use CountDownLatch for example. Create
CountDownLatch latch = new CoundownLatch(1);
First service will call countDown(), when finishes his work.
//service1
public void run(){
doSmthng();
latch.countDown();
}
And second service will wait until latch counter not equals 0.
//service2
public void run(){
latch.await();
doSmthngElse();
}

Runnable running every 20 seconds instead of the specified delay

The idea is for my runnable to run every minute.
Instead, it runs in roughly about 20 seconds and I have no idea why.
Below is the code:
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
try{
//Post from Queue & update post
if (NetworkUtils.isConnected()) {
//post from queue
try {
postHelper.postFromQueue();
} catch (IOException e) {
e.printStackTrace();
}
//Update posts
postHelper.updateSolicitations();
}
}
catch (Exception e) {
// TODO: handle exception
}
finally{
//also call the same runnable to call it at regular interval
handler.postDelayed(this, 60000);
}
}
};
I don't know if it's relevant but it's onCreate method of MainActivity.
Maybe you consider using ScheduledExecutorService
public static void main(String[] args) {
ScheduledExecutorService execService
= Executors.newScheduledThreadPool(5);
execService.scheduleAtFixedRate(()->{
//The repetitive task, say to update Database
System.out.println("hi there at: "+ new java.util.Date());
}, Delay, Rate, TimeUnit.MILLISECONDS );//TimeUnit.MILLISECONDS is time unit
}
Use a scheduled where you define a quartz cronjob that is then triggered whenever you defined it.
you can do something like every minute or second or every day at 3 o'clock
Simple Quartz/Cron job setup
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
try{
//Post from Queue & update post
if (NetworkUtils.isConnected()) {
//post from queue
try {
postHelper.postFromQueue();
} catch (IOException e) {
e.printStackTrace();
}
//Update posts
postHelper.updateSolicitations();
}
}
catch (Exception e) {
// TODO: handle exception
}
}
}, 60000);

Java Executor not working on JdbcTemplate

I am trying to execute a query with a jdbcTemplate using an executor object but for some reason the program doesn't go inside the jdbcTemplate.
ExecutorService executor = Executors.newFixedThreadPool(NUMBER_OF_CONCURRENT_THREADS);
executor.execute(new Runnable() {
#Override
public void run() {
inboundJdbcTemplate.query(selectQuery, new RowCallbackHandler() {
#Override
public void processRow(ResultSet rs) throws SQLException {//<-instruction pointer never goes to this line
try {
//buffer.put(buildDataPoint(rs, testPermutationId));
System.out.println(rs.getString(0));
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
});
try {
buffer.put(STOPPING_TOKEN);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Can anyone help me with this stupid bug?
I found a solution to the problem.
I needed a CompletionService in order to make sure that I know when the execution of the JdbcTemplate finishes.
{...
ExecutorService executor = Executors.newFixedThreadPool(NUMBER_OF_CONCURRENT_THREADS);
CompletionService<String> completionService = new ExecutorCompletionService (executor);
completionService.submit(new Runnable() {
#Override
public void run() {
inboundJdbcTemplate.query(selectQuery, new RowCallbackHandler() {
#Override
public void processRow(ResultSet rs) throws SQLException {
try {
buffer.put(buildDP(rs, Id));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "Success");
try{
Future<String> take1 = completionService.take();
String s = take1.get();
if(!"Success".equals(s)) throw new RuntimeException("Error Occured");
catch (InterruptedException | ExecutionException e) {
LOG.error(" Could not execute DataExtraction",e);}
executor.shutdown();
...}

In Java: how can I make thread watch over another thread?

Sorry if the question is quite simple. I am a beginner.
I have to create thread that calulates something, while the first thread works the other one have to measure if the first thread calculate the function in specified time. If not, it has to throw exception. Else it returns the answer.
I'd take the java.util.concurrent components - simple example
public void myMethod() {
// select some executor strategy
ExecutorService executor = Executors.newFixedThreadPool(1);
Future f = executor.submit(new Runnable() {
#Override
public void run() {
heresTheMethodToBeExecuted();
}
});
try {
f.get(1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// do something clever
} catch (ExecutionException e) {
// do something clever
} catch (TimeoutException e) {
// do something clever
}
}
Have your thread notify a synchronization object when it is done and have your other thread wait x number of milliseconds for it to finish.
public class Main {
private static final Object mThreadLock = new Object();
static class DoTaskThread extends Thread {
public void run() {
try {
int wait = new Random().nextInt(10000);
System.out.println("Waiting " + wait + " ms");
Thread.sleep(wait);
} catch (InterruptedException ex) {
}
synchronized (mThreadLock) {
mThreadLock.notifyAll();
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
synchronized (mThreadLock) {
DoTaskThread thread = new DoTaskThread();
thread.start();
try {
// Only wait 2 seconds for the thread to finish
mThreadLock.wait(2000);
} catch (InterruptedException ex) {
}
if (thread.isAlive()) {
throw new RuntimeException("thread took too long");
} else {
System.out.println("Thread finished in time");
}
}
}
}
join is a lot simpler than using a lock.
join (millis)
Waits at most millis milliseconds
for this thread to die. A timeout of 0
means to wait forever.
Example code:
Thread calcThread = new Thread(new Runnable(){
#Override
public void run() {
//some calculation
}
});
calcThread.start();
//wait at most 2secs for the calcThread to finish.
calcThread.join(2000);
//throw an exception if the calcThread hasn't completed.
if(calcThread.isAlive()){
throw new SomeException("calcThread is still running!");
}
Have a look at http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ExecutorService.html#awaitTermination(long,%20java.util.concurrent.TimeUnit) which allows you to handle this without dealing with thread synchronization yourself.

Categories

Resources