Unable to set a boolean flag from scheduled executor service - java

I need to run a piece of code periodically. This code checks a condition and sets a boolean flag.
In order to run it periodically, I am using scheduledExecutorService.scheduleAtFixedRate method.
The scheduler works fine, but it is unable to set the flag.
The flag value is always false.
Please advise.
package healthCheck;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Test {
private static ScheduledExecutorService scheduler;
public static void main(String[] args)
throws InterruptedException, ExecutionException {
scheduler = Executors.newSingleThreadScheduledExecutor();
Future<?> scheduledFuture = scheduler.scheduleAtFixedRate(
new SomeFiveSecondelyJob(), 1, 5, TimeUnit.SECONDS);
System.out.println("Flag at scheduler"+scheduledFuture.get());
}
public static void contextDestroyed() {
scheduler.shutdownNow();
}
}
The Runnable code:
package healthCheck;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class SomeFiveSecondelyJob implements Runnable {
#Override
public void run() {
URL url;
try {
url = new URL("https://www.google.co.in/");
HttpsURLConnection connection =
(HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
int code = connection.getResponseCode();
if (code / 100 == 2) {
ItSystemFlag.setFlag(true);
System.out.println("System is up");
} else {
ItSystemFlag.setFlag(false);
System.out.println("System unavailable: " + code);
}
} catch (Exception e) {
ItSystemFlag.setFlag(false);
e.printStackTrace();
}
System.out.println(ItSystemFlag.getFlag());
}
}
I am using a static volatile variable as a flag:
package healthCheck;
public class ItSystemFlag {
private static volatile Boolean flag = false;
public static void setFlag(Boolean flag) {
ItSystemFlag.flag = flag;
System.out.println("seting the flag to :" + ItSystemFlag.flag);
}
public static Boolean getFlag() {
return ItSystemFlag.flag;
}
}
Second client class:
package healthCheck;
public class Test2 {
public static void main(String[] args) throws InterruptedException {
for(int i=0;i<20;i++) {
System.out.println("From client "+ItSystemFlag.getFlag());
Thread.sleep(6000);
}
}
}

These are two different java processes. The global variable is not shared between them. Try:
public class Test {
private static ScheduledExecutorService scheduler;
public static void main(String[] args)
throws InterruptedException, ExecutionException {
scheduler = Executors.newSingleThreadScheduledExecutor();
Future<?> scheduledFuture = scheduler.scheduleAtFixedRate(
new SomeFiveSecondelyJob(), 1, 5, TimeUnit.SECONDS);
System.out.println("Flag at scheduler"+scheduledFuture.get());
for(int i=0;i<20;i++) {
System.out.println("From client "+ItSystemFlag.getFlag());
Thread.sleep(6000);
}
}
public static void contextDestroyed() {
scheduler.shutdownNow();
}
}
First run the scheduler and then in the same java process check the global flag.

Related

How can I manage multiple callable threads result without a specific order?

Basically something like this:
ExecutorService service = Executors.newFixedThreadPool(2);
Future<Boolean> futureFoo = service.submit(myFooTask);
Future<Boolean> futureBar = service.submit(myBarTask);
int resultFoo;
boolean resultBar;
resultFoo = futureFoo.get();
resultBar = futureBar.get();
I want to do an event to manage independently the first result I get, without waiting for futureFoo to finish first.
you can use CompletionService. The results of the callables are put in a queue, and you can take the results of the tasks as soon as they complete. in this case, you don't need to wait for the results of Foo if Bar completes earlier. for example:
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class CompletionServiceExample {
private static Logger LOGGER = Logger.getLogger("CompletionServiceExample");
public static void main(String[] args) throws InterruptedException {
CompletionServiceExample completionServiceExample = new CompletionServiceExample();
completionServiceExample.doTheWork();
}
private void doTheWork() throws InterruptedException {
final ExecutorService executorService = Executors.newFixedThreadPool(2);
final CompletionService<Boolean> completionService = new ExecutorCompletionService<>(executorService);
completionService.submit(new Foo());
completionService.submit(new Bar());
int total_tasks = 2;
for(int i = 0; i < total_tasks; ++i) {
try {
final Future<Boolean> value = completionService.take();
System.out.println("received value: " + value.get());
} catch (ExecutionException e) {
LOGGER.log(Level.WARNING, "Error while processing task. ", e);
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "interrupted while waiting for result", e);
}
}
executorService.shutdown();
executorService.awaitTermination(5, TimeUnit.SECONDS);
}
}
class Foo implements Callable<Boolean> {
#Override
public Boolean call() throws Exception {
Thread.sleep(5000);
return true;
}
}
class Bar implements Callable<Boolean> {
#Override
public Boolean call() throws Exception {
Thread.sleep(1000);
return false;
}
}
If you want to return different types, you can use a base class and do downcasting. for example like this:
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class CompletionServiceExample {
private static Logger LOGGER = Logger.getLogger("CompletionServiceExample");
public static void main(String[] args) throws InterruptedException {
CompletionServiceExample completionServiceExample = new CompletionServiceExample();
completionServiceExample.doTheWork();
}
private void doTheWork() throws InterruptedException {
final ExecutorService executorService = Executors.newFixedThreadPool(2);
final CompletionService<Base> completionService = new ExecutorCompletionService<>(executorService);
completionService.submit(new FooBase());
completionService.submit(new BarBase());
int total_tasks = 2;
for (int i = 0; i < total_tasks; ++i) {
try {
final Future<Base> value = completionService.take();
Base base = value.get();
if (base instanceof FooBase) {
int myInteger = ((FooBase) base).getValue();
System.out.println("received value: " + myInteger);
}
if (base instanceof BarBase) {
boolean myBoolean = ((BarBase) base).isValue();
System.out.println("received value: " + myBoolean);
}
} catch (ExecutionException e) {
LOGGER.log(Level.WARNING, "Error while processing task. ", e);
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "interrupted while waiting for result", e);
}
}
executorService.shutdown();
executorService.awaitTermination(5, TimeUnit.SECONDS);
}
}
class Base {
}
class FooBase extends Base implements Callable<Base> {
private int value;
#Override
public Base call() throws Exception {
Thread.sleep(5000);
value = 10;
return this;
}
public int getValue() {
return value;
}
}
class BarBase extends Base implements Callable<Base> {
private boolean value;
#Override
public Base call() throws Exception {
Thread.sleep(1000);
value = false;
return this;
}
public boolean isValue() {
return value;
}
}

Java: ExecutorService and Callables, unable to catch exception

I'm trying to figure out why the below code doesn't print out the stack trace of a NumberFormatException when I run it?
I'm not sure if it is common to use callables and ExecutorService in this way, I googled and couldn't find a solution to my problem... there may be something really obvious that I'm not seeing.
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CallablesTest {
private final static ArrayList<Callable<Void>> mCallables = new ArrayList<>();
private final static ExecutorService mExecutor = Executors.newFixedThreadPool(4);
public static void main(String[] args) throws Exception{
testMethod();
}
static void testMethod() throws Exception {
mCallables.clear();
for(int i=0; i<4; i++){
mCallables.add(new Callable<Void>() {
#Override
public Void call() throws Exception {
//if (Thread.currentThread().isInterrupted()) {
// throw new InterruptedException("Interruption");
//}
System.out.println("New call");
Double.parseDouble("a");
return null;
} //end call method
}); //end callable anonymous class
}
try {
mExecutor.invokeAll(mCallables);
mExecutor.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I think I may have found the answer to my own question... if you get the future objects returned from ExecutorService.invokeAll... and then surround the Future "get" calls with a try/catch block, you can catch the exception
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ThreadTest {
private final static ArrayList<Callable<Boolean>> mCallables = new ArrayList<>();
private final static ExecutorService mExecutor = Executors.newFixedThreadPool(4);
public static void main(String[] args) throws Exception{
testMethod();
}
static void testMethod() throws Exception {
mCallables.clear();
for(int i=0; i<4; i++){
mCallables.add(new Callable<Boolean>() {
#Override
public Boolean call() throws Exception {
//if (Thread.currentThread().isInterrupted()) {
// throw new InterruptedException("Interruption");
//}
System.out.println("New call");
double d = Double.parseDouble("a");
return true;
} //end call method
}); //end callable anonymous class
}
try {
List<Future<Boolean>> f= mExecutor.invokeAll(mCallables);
f.get(1).get();
f.get(2).get();
f.get(3).get();
f.get(0).get();
} catch (Exception e) {
String s = e.toString();
System.out.println(s);
}
mExecutor.shutdown();
}
}

Unexpected behaviour with Java timer task

My Timer task is not functioning as it's supposed to. I have scheduled it to repeat a specific task every 3 seconds but this is not happening.
As per Java documentations:
schedule(TimerTask task, long delay,long period) .
Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.
public class Tester {
public static void main(String[] args) {
log.info("Schedule task");
Timer time = new Timer();
TesterClient tc = new TesterClient();
time.schedule(tc, 0, 3000);
}
}
public class TesterClient extends TimerTask {
public void init() {
System.out.println("New Task!!!!");
}
#Override
public void run() {
init();
}
}
And yet i only get one "New Task!!!!" printed in console
Am i missing something here?
Thanks
Update:
I will try to paste in here every piece of code that is relevant and goes from top to bottom in terms of execution.
Start:
public class Tester {
public static Logger log = Logger.getLogger("com.orderlysoftware.orderlycalls.manager.ManagerClient");
public static Timer time = new Timer();
public static void main(String[] args) {
log.info("Creating service");
Service.serviceInit();
log.info("Initializing TesterClient for scheduled task");
TesterClient tc = new TesterClient();
time.schedule(tc, 0, 3000);
}
public static ManagerSettings managerSettings() {
ManagerSettings managerSettings = new ManagerSettings();
managerSettings.setName("managerClient");
managerSettings.setHost("77.237.251.152");
managerSettings.setPort(5038);
managerSettings.setUsername("orderlystats");
managerSettings.setPassword("orderlystats");
return managerSettings;
}
}
Service class method:
static ExecutorService executorService;
{
serviceInit();
}
//public static ClassLoader loader;
public static void serviceInit(){
if(executorService!=null) {
return;
}
executorService= Executors.newCachedThreadPool();
try {
ThreadPoolExecutor tpe=(ThreadPoolExecutor)executorService;
tpe.setMaximumPoolSize(100000);
} catch (Exception ex) {
System.out.println(ex);
}
}
package com.orderlysoftware.testing;
import java.io.IOException;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.logging.Logger;
import com.orderlysoftware.orderlycalls.OrderlyCalls;
import com.orderlysoftware.orderlycalls.asterisk.manager.ManagerClient;
import com.orderlysoftware.orderlycalls.asterisk.manager.action.ManagerResponse;
import com.orderlysoftware.orderlycalls.asterisk.manager.event.ManagerEvent;
import com.orderlysoftware.orderlycalls.asterisk.manager.event.ManagerEventListener;
import com.orderlysoftware.orderlycalls.base.Service;
public class TesterClient extends TimerTask {
public static Logger log = Logger.getLogger("com.orderlysoftware.orderlycalls.manager.ManagerClient");
public static ExecutorService es = Service.getExecutorService();
public ManagerClient mc;
public void init() {
log.info("run check method to see if Manager Client is running");
boolean running = check();
log.info("checker status is : " + running);
while(running) {
try {
Thread.sleep(3000);
startCall();
} catch (InterruptedException e) {
log.info("Sleep interrupted");
}
}
}
public boolean check() {
log.info("ManagerClient is: " + mc);
if(mc == null) {
log.info("Initialize service");
mc = (ManagerClient)OrderlyCalls.createService(ManagerClient.class, Tester.managerSettings());
log.info("Initialize ManagerClient");
mc.init();
log.info("Service created. ManagerClient initialized : "+ mc);
}
if(!mc.isConnected()) {
log.info("ManagerClient is not connected");
return false;
}
log.info("Check if ManagerClient is connected AND running");
if(mc.isConnected() && !mc.isRunning()) {
log.info("Manager Client is connected but NOT running");
return false;
}
if(mc.isConnected() && mc.isRunning()) {
log.info("ManagerClient is connected and running");
return true;
}
return false;
}
private void startCall() {
log.info("Adding listener to the call");
addListenerToCall(mc);
int testID = 0;
ManagerResponse response = null;
try {
response = mc.originate("Local/1001#main", "1001", "main", "1", null, null, 2500, "1002", "testID=" + (testID++), "1", true);
log.info("Manager response is: " + response);
if(response == null) {
mc.shutdown();
throw new IOException("Null response for originate.");
}
if(!response.getValue("Response").equals("Success")) {
mc.shutdown();
throw new IOException("Originate returned " + response.getValue("Response") + ": " + response.getValue("Message"));
}
} catch (IOException e) {
log.info("IO Exception" + e.toString());
}
}
public void addListenerToCall(ManagerClient mc) {
try {
// Add event listener
log.info("Adding ManagerEventListener to ManagerClient: " + mc);
mc.addManagerEventListener(new ManagerEventListener() {
#Override
public void handleManagerEvent(ManagerEvent event) {
if("OriginateResponse".equals(event.getType())) {
handleOriginateResponse(event);
}
}
});
} catch (IOException e) {
log.info("IO Exception : " + e);
}
}
protected void handleOriginateResponse(ManagerEvent event) {
try {
// do something here
Thread.sleep(1000);
} catch (InterruptedException e) {
log.info("sleep interupted" + e);
}
}
#Override
public void run() {
log.info("New Task!!!!!!!!!!");
init();
}
}
It works for me - but I suspect the problem is that you're letting the Timer get garbage collected:
After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread terminates gracefully (and becomes subject to garbage collection). However, this can take arbitrarily long to occur.
As noted in comments, I believe that "outstanding tasks" means "tasks that have already been started" rather than just "ones which would be scheduled". The docs are unclear, however, and I may be mistaken.
If you prevent garbage collection (e.g. by keeping a reference to the Timer in a static variable) then I think you'll see it keep going forever...
Your program works fine for me too. The issue got reproduced with following change in your program:
import java.util.*;
public class Tester {
public static void main(String[] args) {
System.out.println("Schedule task");
Timer time = new Timer();
TesterClient tc = new TesterClient();
time.schedule(tc, 0, 3000);
}
}
class TesterClient extends TimerTask {
public void init() {
System.out.println("New Task!!!!");
}
#Override
public void run() {
init();
this.cancel(); //-------This causes hang in execution after printing once
}
}
But, not sure what could have caused this to happen without cancel() in your program.

Time out a java code?

I am writing an online java programming app where I take a java code as input from user and returns the output after compilation and execution through a python script.
For controlling the memory heap I have a standard solution of using -Xms and -Xmx while running the code in JVM. I have installed Sun Java 1.7.0_40.
Now the problem is that I am confused about how to restrict the code with a time limit. For example any code submitted by user in my app should not run for more than T seconds, where T is a variable.
I wrote one simple hack using Timer class but the problem is I have to use a lot of regex to inject it in the user code which I primarily want to avoid. As I am more comfortable in python and c++ than java as a programmer, I need some guidance about whether there exists some easy solution for such problem or what are the pros and cons of using the Timer class.
Any help will be much appreciated!
Thanks
I've done simple 'TimeoutThread' util using by ExecutorService.
2 classes:
package eu.wordnice.thread;
/*** Runa.java ***/
import java.util.concurrent.Callable;
public class Runa implements Callable<Object> {
private Runnable run = null;
public Runa(Runnable run) {
this.run = run;
}
public Runa(Thread run) {
this.run = run;
}
public Runa() {}
public Object call() throws Exception {
if(run != null) {
run.run();
}
return -1;
};
}
And:
package eu.wordnice.thread;
/*** TimeoutThread.java ***/
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class TimeoutThread {
public Runa run = null;
public ExecutorService executor = null;
public long timeout = 100L;
private boolean canceled = false;
private boolean runed = false;
public TimeoutThread(Runnable runit, long timeout) {
this(new Runa(runit), timeout);
}
public TimeoutThread(Runa runit, long timeout) {
this.run = runit;
if(timeout < 1L) {
timeout = 10L;
}
this.timeout = timeout;
}
public Object run() {
return this.run(false);
}
public Object run(Object defaulte) {
this.runed = true;
List<Future<Object>> list = null;
try {
this.executor = Executors.newCachedThreadPool();
list = executor.invokeAll(Arrays.asList(this.run), this.timeout, TimeUnit.MILLISECONDS);
} catch (Exception e) {
e.printStackTrace();
this.canceled = true;
}
executor.shutdown();
if(list == null) {
return defaulte;
}
if(list.size() != 1) {
return defaulte;
}
try {
Future<Object> f = list.get(0);
try {
return f.get();
} catch (Exception e) {
this.canceled = true;
}
} catch (Exception e) { }
return defaulte;
}
public boolean wasRunned() {
return this.runed;
}
public boolean wasCanceled() {
return this.canceled;
}
}
Example:
public static void main(String... blah) {
TimeoutThread thr = new TimeoutThread(new Runa() {
#Override
public Object call() throws Exception {
while(true) {
System.out.println("Yeeee");
Thread.sleep(300L);
}
}
}, 500L);
thr.run();
}
Print:
Yeeee
Yeeee
EDIT!
Sorry, that is Timeout Runnable. If you want Timeout Tread, just put the code / call into Thread.
public static void main(String... blah) {
final TimeoutThread thr = new TimeoutThread(new Runa() {
#Override
public Object call() throws Exception {
while(true) {
System.out.println("Yeeee");
Thread.sleep(300L);
}
}
}, 500L);
new Thread() {
#Override
public void run() {
thr.run(); //Call it
}
}.start(); //Run it
}
I would have a look at using ExecutorService in Java for this and have the class with the functionality you want to time out implement runnable - so using Java's threading capabilities to help you out.
You should be able to timeout the thread using the following code:
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.invokeAll(Arrays.asList(new Task()), 10, TimeUnit.MINUTES); // Timeout of 10 minutes.
executor.shutdown();
But you may need to check out the documentation a bit to get it to work for your use case.
See the following post for more advice on this kind of thing.
Not sure if you're wanting to have the timeout in your python code or in Java, but hopefully this'll help a bit.
You can use ThreadPoolExecutor
sample:
int corePoolSize = 5;
int maxPoolSize = 10;
long keepAliveTime = 5000;
ExecutorService threadPoolExecutor =
new ThreadPoolExecutor(
corePoolSize,
maxPoolSize,
keepAliveTime,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()
);
threadPoolExecutor.execute(new Runnable(){
#Override
public void run() {
// execution statements
});
References
http://tutorials.jenkov.com/java-util-concurrent/threadpoolexecutor.html

Awaitility.await().atMost(...) causes program to exit if time out interval expires?

This question regards com.jayway.awaitility.Awaitility.
I just tried Awaitility.await() and it seems to have some odd behavior.
In the test method below if I comment out testWithFuture() and enable
testWithAwaitility(), I never see the message "end " printed out.
I see 'start ', then the program just exits, and the second
print statement never seems to be reached.
So as a work around I decided to use Settable{Future}.. If anyone else has the same issue then maybe the work-around I provide will be useful.. Even better would be to get a nice answer ;^) ! thanks in advance / chris
THE CODE:
import com.google.common.util.concurrent.SettableFuture;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static com.jayway.awaitility.Awaitility.await;
import static java.util.concurrent.TimeUnit.SECONDS;
public class AwaitTest {
static volatile boolean done = false;
public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
testWithFuture();
//testWithAwaitility();
}
private static void testWithAwaitility() {
System.out.println("start " + new Date());
new Thread(new Runnable(){
public void run(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
done = true;
}
}).start();
await().atMost(2, SECONDS).until(new Callable() {
#Override
public Boolean call() throws Exception {
return done;
}
});
System.out.println("end " + new Date()); // NEVER Reached. i wonder why?
}
// This does what I want.
//
private static void testWithFuture() throws InterruptedException, ExecutionException, TimeoutException {
System.out.println("start testWithFuture");
final SettableFuture future = SettableFuture. create();
new Thread(new Runnable(){
public void run(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
future.set("Hello");
}
}).start();
String result = future.get(4, TimeUnit.SECONDS);
if (! result.equals("Hello")) {
throw new RuntimeException("not equal");
} else {
System.out.println("got Hello");
}
}
}
CORRECTED CODE ->
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static com.jayway.awaitility.Awaitility.await;
import static java.util.concurrent.TimeUnit.SECONDS;
public class Sample {
static volatile boolean done = false;
public static void main(String[] args) {
testWithAwaitility();
}
private static void testWithAwaitility() {
System.out.println("start " + new Date());
new Thread(new Runnable(){
public void run(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
done = true;
}
}).start();
try {
await().atMost(2, SECONDS).until(new Callable() {
#Override
public Boolean call() throws Exception {
return done;
}
});
} catch (Exception e) {
System.out.println("FAILED");
e.printStackTrace();
}
System.out.println("end " + new Date()); // REACHED this statement after correction
}
}
According to the documentation, await() throws a TimeoutException if the timeout is reached and the condition is not true, so your method ends at this point because the exception is propagated up through the stack. This explains the behavior. You should see a stacktrace, however.
If you want to continue executing code afterwards, it seems you would need to catch this exception.

Categories

Resources