You're got more of an architectural problem to solve first. In a single-threaded program the sequence is normally:
- Do stuff;
- Call sendTo();
- Do more stuff.
You have to work out if what you want is:
- Do stuff;
- Call sendTo();
- If (2) fails, wait 10 seconds and sendTo() again;
- If (3) fails, throw an error;
- Do more stuff.
The point being that this is still synchronous. If so you'll need a thread. You should use the Java 5 Executors.
public void sendTo(final String username, final String message) {
if (!internalSendTo(username, message)) {
// attempt resend
ExecutorService exec = Executors.newSingleThreadExecutor();
final AtomicBoolean result = new AtomicBoolean(false);
exec.submit(new Runnable() {
boolean b = internalSendto(username, message);
result.set(b);
});
try {
exec.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// still didn't work
} finally {
exec.shutdownNow();
}
}
}
private boolean internalSendTo(String username, String message) {
Userdata user = findUser(username);
boolean success = false;
if (user != null) {
Out out = new Out(user.getClientSocket());
// do the communication here
success = true;
}
return success;
}
Now that's just a rough sketch of how it might work. It should give you some appreciation for the issues however.
Do you want this or do you want:
- Do stuff;
- Call sendTo();
- If (2) fails, queue the send and keep going;
- Do more stuff.
Basically this is the asynchronous approach. If you go this way you then have to answer questions like:
- What happens if after 10+ seconds (or some arbitrary interval) it still hasn't worked?
- What processes attempt the sendTo() calls?
- What if they block/die?
- Do I need multiple senders?
- etc
Basically it gets much more complicated.