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.
Related
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();
}
}
I am using the GitHub API, but it throws an exception because of the rate limit.
I use catch to catch this exception, but I want to use a timer count 1 hour and continue the function from where it stopped.
try{
// my function
}
catch (NoSuchPageException e ) {
Thread.sleep(3600 * 1000);
System.out.println("Waiting the timer");
}
How can I continue my function after the timer ends?
I suppose you can use a while loop.
boolean continueFunc = false;
while (!continueFunc)
try{
//my function
continueFunc = true;
}
catch (NoSuchPageException e ){
Thread.sleep(3600 * 1000);
System.out.println("Waiting the timer");
}
}
Your question is unclear but if you wish to retrieve html content but continue if you content is not there 1 hour later after calling the function you can use futures:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
public class FutureExample {
static class RetrieveHTMLThingy implements Callable<String> {
#Override
public String call() throws Exception {
System.out.println("Getting HTML Stuff");
Thread.sleep(2000);
return "html stuff";
}
}
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
FutureTask<String> getHTML = new FutureTask<String>(new RetrieveHTMLThingy());
executor.execute(getHTML);
try {
System.out.println(getHTML.get(1, TimeUnit.HOURS));
} catch (Exception e) {
e.printStackTrace();
}
}
}
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.
I want to capture an AXIS camera & stream it. I am quite new to RED5. I get the following error:
Exception in thread "main" java.lang.NullPointerException at
org.vikulin.rtmp.publisher.Publisher2.packetReceived(Publisher2.java:23)
at
org.red5.server.presentation.output.flv.FLVStream.dispatchEvent(FLVStream.java:243)
at
org.red5.server.presentation.output.flv.FLVStream.sendAVCDecoderConfig(FLVStream.java:162)
at
org.red5.server.presentation.output.flv.FLVStream.addEvent(FLVStream.java:76) at
org.red5.server.presentation.MediaPresentation.onMediaEvent(MediaPresentation.java:43)
at
org.red5.server.presentation.input.avp.codecs.H264.addPacket(H264.java:206)
at
org.red5.server.presentation.RTSPStream.onRTSPEvent(RTSPStream.java:100)
at
org.red5.server.net.rtsp.proxy.RtspTcp.setupAndPlay(RtspTcp.java:287)
at org.red5.server.presentation.RTSPStream.onSDP(RTSPStream.java:138)
at
org.red5.server.net.rtsp.proxy.RtspTcp.parseDescription(RtspTcp.java:128)
at org.red5.server.net.rtsp.proxy.RtspTcp.describe(RtspTcp.java:64)
at
org.red5.server.presentation.RTSPStream.startInput(RTSPStream.java:77)
at org.red5.server.presentation.RTSPStream.start(RTSPStream.java:82)
at org.vikulin.rtmp.publisher.Publisher2.main(Publisher2.java:49)
Here is the code:
import java.io.IOException;
import org.red5.server.api.stream.IBroadcastStream;
import org.red5.server.api.stream.IStreamListener;
import org.red5.server.api.stream.IStreamPacket;
import org.red5.server.net.rtmp.event.VideoData;
import org.red5.server.presentation.RTSPStream;
import org.red5.server.stream.message.RTMPMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Publisher2 implements IStreamListener {
PublishClient client;
#Override
public void packetReceived(IBroadcastStream arg0, IStreamPacket arg1) {
System.out.println("" + arg1);
VideoData data = new VideoData(arg1.getData());
RTMPMessage message = RTMPMessage.build(data);
try {
client.pushMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
Logger log = LoggerFactory.getLogger(Publisher2.class);
String publishName = "testb";
String host = "127.0.0.1";
int port = 1935;
String app = "live";
PublishClient client = new PublishClient();
client.setHost(host);
client.setPort(port);
client.setApp(app);
client.start(publishName, "live", null);
while (client.getState() != PublishClient.PUBLISHED) {
Thread.sleep(500);
}
Publisher2 test = new Publisher2();
final RTSPStream camera = new RTSPStream("192.168.254.115", 554,
"rtsp://192.168.254.115/axis-media/media.amp?videocodec=h264&videokeyframeinterval=30&fps=30");
camera.addStreamListener(test);
new Thread(new Runnable() {
#Override
public void run() {
camera.start();
}
}).start();
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
camera.stop();
try {//wait for write out.
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
client.stop();
}
}
If you have any idea please help me!
You declared a client variable in your main method, but in your packetReceived method, you reference the class variable. The class variable is still null at that point. So, possibly change this line:
PublishClient client = new PublishClient();
to this:
client = new PublishClient();
or pass the client in to your method, and remove variable declaration from your class.
My Program looks like below
Main Program (Thread 1)
Create multiple simple java threads (Thead 1.1, 1.2...)
In each thread(1.1 or 1.2..) I'm doing some processing also calling one method which is
sometimes is not responding(CORBA calls). I want to define timer for
this method and thread(1.1 or 1.2 whoever is calling) should wait there itself till I get response or timer expired.
I have written following sample program. I don't think this is the right approach. Is there any better approach? In this prg I'm not sure when the interupt method is invoked.
public class MethodTimeout implements Runnable{
/**
* #param args
*/
public Thread t1 = null;
public int threadnum = 0;
public static void main(String[] args) {
for (int i=0; i<3; i++){
MethodTimeout mt =new MethodTimeout();
Thread t = new Thread(mt,"thread "+(i+1));
mt.t1 = t;
mt.threadnum = (i+1);
t.start();
}
System.out.println("stmt after execution");
}
public Object testTimeout(){
long startTime = System.currentTimeMillis();
try {
System.out.println("in side method start "+t1.getName()+" start time"+startTime);
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long endtime = System.currentTimeMillis();
System.out.println("in side method end "+t1.getName()+" total time"+(endtime-startTime) );
return null;
}
#Override
public void run() {
Thread timeout = new Thread (){
public void run() {
testTimeout();
};
};
timeout.start();
try {
Thread.sleep(2000);
timeout.interrupt();
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(t1.getName() + " is ending");
}
}
This very much sounds like you should implement Callable. This is just an example
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class Test {
public static void main(String[] args) throws Exception {
ExecutorService service = Executors.newFixedThreadPool(2);
Future<String> futureResult = service.submit(new MyCall());
try{
String result = futureResult.get(20, TimeUnit.MILLISECONDS);
} catch(TimeoutException timeout){
System.out.println("Timeout");
service.shutdownNow();
}
}
static class MyCall implements Callable<String> {
#Override
public String call() throws Exception {
try{
//Simulate some corba work
Thread.sleep(1000);
}catch(InterruptedException e){
Thread.currentThread().interrupt();
System.out.println("Shutting down the task!");
}
return "The result";
}
}
}
You can also make one minor change to #Eugene's answer, that is instead of calling the shutdownNow() on the ExecutorService itself you can just call cancel(true) on the futureResult that timed out. Here is the code snippet:
public class Test {
public static void main(String[] args) throws Exception {
ExecutorService service = Executors.newFixedThreadPool(2);
Future<String> futureResult = service.submit(new MyCall());
try{
String result = futureResult.get(20, TimeUnit.MILLISECONDS);
} catch(TimeoutException timeout){
System.out.println("Timeout");
} finally {
futureResult.cancel(true);
}
}
This is just to ensure that only the timed out thread is cancelled. As the shutdownNow() prevents waiting tasks from starting in addition to attempting to stop currently executing ones.