Java - How to measure a time out - java

I am making a ping program using Java sockets. One bug in my program is that sometimes it will not connect and will just sit there for ever. So I am trying to add a timeout (after twenty seconds) and the ping will fail. But I have no idea how to.
Here is part of my ping program:
boolean result = false;
long before1 = System.nanoTime();
out.println(new byte[64]);
System.out.println("(1) Sent 64 bytes of data to " + address
+ "...");
try {
if ((in.readLine()) != null) {
int size = in.readLine().toString().getBytes().length;
long after = System.nanoTime();
long s = ((after - before1) / 1000000L) / 1000;
System.out.println("(1) Recieved reply from " + address
+ " (" + size + " bytes), time = " + s
+ " seconds...");
result = true;
} else if ((in.readLine()) == null) {
long after = System.nanoTime();
long s = ((after - before1) / 1000000L) / 1000;
System.out.println("(1) Failed to recieve reply from "
+ address + ", time = " + s + " seconds...");
result = false;
}
} catch (IOException exc) {
long after = System.nanoTime();
long s = ((after - before1) / 1000000L) / 1000;
System.err.println("(1) Failed to recieve reply from "
+ address + ", time = " + s + " seconds...\nReason: "
+ exc);
result = false;
}
But I would like to measure time elapsed any where in my code, instead of:
long time = System.nanoTime();
If one part of my code is stuck doing something it will time out after 20 seconds.
Any suggestions on how to measure if twenty seconds has passed at the start of a try/catch block or anywhere else in my code so it doesn't get stuck during the ping?

As "jsn" and "jahory" said you need to do this with threads. Here's 2 useful links, you can check them ;)
How to implement timeout using threads
Adding a thread timeout to methods in Java

You can use Future and FutureTask:
ExecutorService pingExecutor = ... // executor service to run the ping in other thread
void showPing(final String target) throws InterruptedException {
Future<String> ping = executor.submit(new Callable<String>() {
public String call() {
String pingResult = ... // do your Ping stuff
return pingResult;
}});
System.out.println("Pinging..."); // do other things while searching
try {
System.out.println(future.get(20, TimeUnit.SECONDS)); // use future, waits 20 seconds for the task to complete
} catch (ExecutionException ex) {
} catch (TimeoutException tex) {
// Ping timed out
}
}

You can find some hints here: How do I call some blocking method with a timeout in Java?
Future interface looks like a good solution to your problem. Remember, however, that depending on what your task is doing, you probably would be not able to really cancel it. Additional info:
tutorial (see, in particular, Non-blocking algorithms section)

Related

#RabbitListener how to set frequency of receiving messages in annotation

I am using #RabbitListner annotation to recieve messages from a RabbitMq queue.
How to make threads receive messages no more often than 1 second?
#RabbitListener(queues = "message", priority = "3",concurrency = "2")
public void receiveCheck(RequestMessage message){
}
Your task is a bit strange. Don't you think that the problem should be solved differently (maybe you can send messages with a certain frequency - 1 message/sec)?
But if you're sure that's what you need, you could use primitive solution:
#RabbitListener(queues = "message", priority = "3", concurrency = "2")
public void receiveMessage(String message) throws InterruptedException {
System.out.println("Received <" + message + ">" + " Message time: " + LocalDateTime.now());
Thread.sleep(1000);
}
Or with the calculation of the operation time:
#RabbitListener(queues = "message", priority = "3", concurrency = "2")
public void receiveMessageWithTimer(String message) throws InterruptedException {
long start = System.currentTimeMillis();
System.out.println("Received <" + message + ">" + " Message time: " + LocalDateTime.now());
long finish = System.currentTimeMillis();
long operationTime = finish - start;
Thread.sleep(1000 - operationTime);
}
But in this case you should remeber that concurrency level = 2. And you will receive 2 message/sec.
For receiving of only one message you could set concurrency level = 1.

Alarm Code in java using Netbeans IDE

Hi Guys First of all I must say thanks to all of you guys for helping me :). I was a silent member before this query and benefited a lot from other members question.
But now I'm stuck in my code. See I'm developing a software that will help EVENT MANAGEMENT. I have done all that basics of creating and saving events in the database - i'm using sqlite db.
I'm stuck for code of pop-up and alarm when event time is started.
I saved date as String in db which is in this format "26-04-2015".
I saved time as String in db which is in this format "17:00:00".
What I've tried uptil now is this - I was comparing current time with that on db but failed to make it work)
Any suggestion or help will be highly appreciated.
private void checkAlarm() {
new Thread() {
Calendar cal = new GregorianCalendar();
int hour = cal.get(Calendar.HOUR);
int min = cal.get(Calendar.MINUTE);
int sec = cal.get(Calendar.SECOND);
String time = hour + ":" + min + ":" + sec;
String[] data = connect.readData1("Select e_sdate, e_stime,e_title from tbl_event order by e_sdate ASC limit 1", "e_stime", "e_title");
String sTime = data[0];
String title = data[1];
public void run() {
while (true) {
try {
Thread.sleep(1000);
System.out.println("time from db : " + sTime);
System.out.println("time current : " + time);
} catch (Exception e) {
}
if (time.equals("sTime")) {
try {
TrayIcon icon = new TrayIcon(getIconImage(), "Event Management System", createPopupMenu());
playSound();
icon.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "This event has been started now.");
}
});
SystemTray.getSystemTray().add(icon);
Thread.sleep(3000);
icon.displayMessage("Event : " +title, "Event Time : " +sTime, TrayIcon.MessageType.INFO);
} catch (Exception e) {
System.out.println("Tray Icon Error : " +e);
}
}
}
}
}.start();
}

Trouble in Java TimerTask Interval

Sorry for my bad english.
I'm implementing Java TimerTask when creating an Android application. The code isn't to complicated. When it hit the interval, it will send an SMS & email.
I have some option with the sending SMS / email interval. 5 minutes, 15 minutes, 30 minutes, 1 hour, and 2 hour.
I tried using 5 minutes, and 15 minutes (I converted it into milis), no trouble occurred. It send sms and email every 5 / 15 minutes exactly. And I prove that i have no problem using timertask.
But, when I changed it to 30 minutes or more. my application cannot send sms / email. It looked like that the timer didn't work correctly.
Does it have any interval limitation on using Timer Task ??
this is my code snippet.
private void activateNotificationByInterval(int notificationInterval) {
timerNotificationByInterval = new Timer();
timerNotificationByInterval.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
// coba
// if (oldLatitude != childLatitude
// && oldLongitude != childLongitude) {
if ((enableSMS == true)) {
sendSMS();
}
if ((enableEmail == true)) {
GMailSender email = new GMailSender(sender, senderPassword);
try {
email.sendMail(emailSubject + childsName, SMSMessage
+ " " + childlLocation + "\nLatitude: "
+ childLatitude + "\nLongitude: "
+ childLongitude, sender, destination);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mpv.changeLastLocation(childLatitude, childLongitude);
// buat method untuk menangkap lokasi pertama
oldLatitude = childLatitude;
oldLongitude = childLongitude;
// } else {
// System.out.println("Lokasi Lama Berpengaruh");
// }
}
}, 0, notificationInterval);
}
*notes : notificationInterval on milis (*60000)
can you tell me how to solved it ? thank you.
Use AlarmManager and there is a link here:
http://android-er.blogspot.in/2010/10/simple-example-of-alarm-service-using.html

How to Convert TimeStamps to Ticks (PPQ) - Real Time Midi

I'm currently reading in MIDI messages in real-time from my midi keyboard using a class that implements Receiver, and outputting the notes played.
The only information i receive when I press a note is the MidiMessage and a timeStamp.
I am trying to paint the notes as actual piano sheet music and currently the user has to set the bpm beforehand.
Therefore if I know the tempo is 120bpm (for example), how can I use the timeStamps to determine the length of the note pressed?
I'm assuming if I can convert the timeStamps into ticks (ppq), then I can use that to work out the timings.
Any help is greatly appreciated. Below is my "send" method in my Receiver class.
The 'firstStamp' and 'secondStamp' variables are just to output the length of a note. I took the timeStamp when a note was released and subtracted the timeStamp when it was pressed.
#Override
public void send(MidiMessage message, long timeStamp) {
String strMessage = null;
if (firstStamp == 0) {
firstStamp = timeStamp;
secondStamp = timeStamp;
}
firstStamp = secondStamp;
secondStamp = timeStamp;
stampDif = (secondStamp - firstStamp);
if (message instanceof ShortMessage) {
strMessage = decodeMessage((ShortMessage) message, timeStamp);
} else if (message instanceof MetaMessage) {
strMessage = decodeMessage((MetaMessage) message);
} else if (message instanceof SysexMessage) {
strMessage = decodeMessage((SysexMessage) message);
} else {
strMessage = "other message" + message.getStatus();
}
r_out.println("Timestamp: " + timeStamp + " " + strMessage);
r_printStream.println("Timestamp: " + timeStamp + " " + strMessage);
}
If the timestamp is in milliseconds then you can convert it to ticks like this:
long ticks = timestamp * bpm / (1000 * 60);
Bit you will get a high start tick since the timestamp is probably since Jan 1 1970. So if you want to have your first "tick" as 0 you need to keep track of if this is your first seen event.
if (tickOffset == -1) { // Using -1 as not initialized
tickOffset = ticks;
}
ticks = ticks - tickOffset;

Loop through a ThreadGroup - please help me debugging

I try hard to find the problem in this Java code, but I can't find it - can you help me?
I hope the code I provide is enough, but I will post more if necessary.
Further I apologize, I didn't make a minimal example.
game.getGroupPlayers().list();
MoverThread[] playerThread = game.getPlayers();
System.out.println(playerThread.length);
for (int i = 0; i < playerThread.length; i++) {
try {
System.out.println(i + " -> " +playerThread[i].toString());
returnString += playerThread[i].toString() + "\n";
} catch(NullPointerException e) {
System.out.println("Problem at i = " + i);
e.printStackTrace();
}
game.getGroupPlayers().list();
}
sometimes gives me the following output:
java.lang.ThreadGroup[name=Players,maxpri=10]
Player-0: 113
Player-1: 277
Player-2: 0
3
0 -> Player-0: 113
1 -> Player-1: 277
Problem at i = 2
java.lang.NullPointerException
at Referee.goalFound(Referee.java:70)
at DebugTestReferee.goalFound(DebugTestReferee.java:42)
at Player.checkGoal(Player.java:61)
at Player.run(Player.java:94)
at java.lang.Thread.run(Thread.java:636)
java.lang.ThreadGroup[name=Players,maxpri=10]
Player-0: 113
Player-1: 277
Player-2: 0
[edit]
here's the source of getPlayers()
/*
* post returns the games players as an array
*/
public MoverThread[] getPlayers() {
synchronized(movers) {
MoverThread[] playerList = new MoverThread[players.activeCount()];
players.enumerate(playerList);
return playerList;
}
}
[edit]
here's how players is generated
private ThreadGroup movers;
private ThreadGroup players;
private ThreadGroup ghosts;
private Observer observer;
/*
* constructor
*/
public Game(Maze maze, Referee referee) {
this.maze = maze;
this.referee = referee;
threadList = new ArrayList<MoverThread>();
movers = new ThreadGroup("Movers");
players = new ThreadGroup(movers, "Players");
ghosts = new ThreadGroup(movers, "Ghosts");
observer = null;
}
[edit]
Here's how I call the method that generates the problem:
/*
* post checks if the players thread was interrupted - if not if hostfield pretends to be a goal the game gets stopped and referee is called to perform "goal-found-actions"
*/
private void checkGoal() {
if (!getThread().isInterrupted()) {
synchronized(getGame().getMovers()) {
if (!getThread().isInterrupted()) {
if (getHostField().isGoal()) {
Field goal = getHostField();
getGame().getReferee().goalFound(this, goal);
getGame().setGameOver();
}
}
}
}
}
and here's the whole goalFound()
/*
* post action to be performed if a player finds a goal
* print some information
*/
public void goalFound(Player player, Field at) {
//FIXME get the Bug!!!
String returnString = "Game over - player " + player.getName() + " found a goal on (" + at.getPos()[0] + ", " + at.getPos()[1] + ")!\n";
game.getGroupPlayers().list();
MoverThread[] playerThread = game.getPlayers();
System.out.println(playerThread.length);
for (int i = 0; i < playerThread.length; i++) {
try {
System.out.println(i + " -> " +playerThread[i].toString());
returnString += playerThread[i].toString() + "\n";
} catch(NullPointerException e) {
System.out.println("Problem at i = " + i);
e.printStackTrace();
}
}
game.getGroupPlayers().list();
returnString += game.mazeString();
System.out.println(returnString);
}
There isn't a nice way of enumerating the Threads of a ThreadGroup. It's a well known terrible design.
Between calling ThreadGroup.activeCount and ThreadGroup.enumerate(Thread[]), threads may have started or died. The best you can do is add a fudge factor the activeCount when allocating the array. If the returned value matches the array length, then you may have missed some and should repeat with a larger array size (probably a factor larger, rather than just adding a constant). When successful, you will need to trim your array appropriately (or treat it as such).
game.getPlayers(); is returning MoverThread[] with length 3, but the third one is null.
I found a solution - or maybe more a workaround...
Beside using ThreadGroups I store my threads in an ArrayList aswell (maybe a Vector would be even better, but I'm fine with the ArrayList).
I don't know why, but when I try to call all Threads in the ThreadGroup it often happens that some Threads are left out. However, with the ArrayList it works fine.
Would be interesting why ThreadGroups don't work as supposed and what we need them for in this case.

Categories

Resources