SocketTimeoutException problem - how to continue after exception - java

I write and read in my function using Socket class. I used
synchronized(socket){
.//write;
//read;
}
I am doing this (repeat) every 50-1000 ms. Problem is when somebody ( unknown reason ) pluged off cable ( I got SocketTimeoutException). When he pluged in again, I need to continue.
What to do ? Do I need to close this socket in catch block and create new ? Or something else ?

You don't have to do anything. Just continue. If you get any other exception, close the Socket and restart (if appropriate).

I'd create a Decorator implementation that was willing to catch a SocketTimeoutException and retry. It could retry a certain number of times, over a certain interval before actually passing the exception along to indicate a "true" (to be defined) error condition. It could even retry indefinitely if you want. The retry logic may even encapsulate re-establishing the socket, though a timeout isn't enough to require that.
Another option is the CircuitBreaker Pattern, though it's not quite designed for what you are describing. CircuitBreaker is a bit better for avoiding costly errors that may be occurring over a period of time.

Related

Dilemma of setting a timeout in ZeroMQ

I currently use ZeroMQ with Java binding. My program is in a PUB/SUB mode.
It seems reasonable to set a timeout, while a client can't receive a message from PUB-side.
But for the publish server, who sends messages without a fixed frequency, it's hard to decide a reasonable timeout.
On the other hand, if no timeout is set, then a program would probably stuck at function:
recv()
forever even publish server is dead.
If there a good solution to fix this issue?
Yes, there is a good solution or two:
A principally best solution is to use a Poller instance, for which a .poll() method tells your code, again with a help of an explicitly configurable aTimeOut in [ms], whether there is any incoming message to either attempt a non-blocking .recv() method or not even trying to do so, once there is NACK for any such message being present from the call to a .poll() method ( for details check the API ).
Another way is to use a non-blocking mode of a call to the .recv( aSockINST, ZMQ_DONTWAIT ) method. Here, the API + wrapper / binding, specify how it handles a state, where none such message was locally ready to get .recv()-ed, so that one may rely on the common language's available syntax-scaffolding - like { try: except: finally: } or { try: catch: } or { defer; panic(); recover() } - to handle either of the return states from the .recv( .., ZMQ_DONTWAIT ) call. Similar rules apply to an ( almost ) blocking call, with some moderately small .recv() timeout.
You can use Pollers:
poller = zmq.Poller()
poller.register(client_receiver, zmq.POLLIN);
for further reading:
http://learning-0mq-with-pyzmq.readthedocs.io/en/latest/pyzmq/multisocket/zmqpoller.html
hope it helps.

Thread Handling after exception

used thread.sleep when exception occurs in my application
if any thing exception occured in any one of the thread it should wait for some time and have to try again
what i am facing the issue means for 100 request if exception occurs for 50 means that should be wait for some time and after try again if any
exception occurs means it should also wait till success
am feeling this going to affect the performance and system usage.
Please let me know your suggestions. Is it better to create new thread if any exception occurs?
Or Any other way?
Retrying on exception isn't a bad idea, but you should make sure that:
The exception is transient (i.e. you have reasons to believe it may
succeed on retry, like a network error)
You have ways to prevent retrying forever (like "max retry")
You don't overload the system by too frequent retries by e.g. using exponential back-off strategy (or even just a reasonably long wait time)
Exception to rule 2 is possible (sometimes you do want stuff to retry forever).
From the question, I understand that, you are talking about RunTimeExceptions.
1) Firstly I would like to suggest that, you should examine the code areas which may really throw the exceptions at run time i.e processing of files.
2) another thing is that you have to handle this scenarios so that exception cases are reduced. i.e first check file is available then only try to read it, check permissions before writing it etc. In this way frequency of retrying may be reduced.
3) If both above actions fails, means the situation which can never be handled such as services are down etc., you can retry the considering all necessary aspects like - MAX try, MAX time out foe which you are re-trying, leave the attempt after certain amount of try OR time etc.
Hope this helps.

Java program and network connection timeout

I have a java program that gather data from the web.
Unfortunately, my network has a problem and it goes off and on.
I need a trick to ask my program wait until the connection is on again and continue its job.
I use the "URLConnection" library to connect. I made a loop to reconnect when it a "ConnectException" is catched, but it doesn't work.
Any suggestions?
my network has a problem and it goes off and on. I need a trick to ask
my program wait until the connection is on again and continue its job
It depends on what your program's purpose is.
How long are these intermittent failures? If they are short enough you could use setConnectTimeout(0) to indicate an infinite timeout period while trying to connect but if your program has to report something back then it is not a good option for the end user.
You could set a relatively low timeout so that when you start to lose the network you will get a java.net.SocketTimeoutException.
When you catch this, you could wait for a period and try again in a loop e.g. for 3 times and then perhaps report a failure.
It depends on what you are trying to do.

How do you know all the exceptions a method can throw

Is there a way to get some details regarding exception safety aspects of Java's standard classes? Mainly working with C++ and C#, I'm confused with Java exception specifications, so I need to understand the proper way of working with exceptions.
To be more specific, let's consider ServerSocket. It starts listening for incoming connections as soon as its object is constructed. Then, you should use accept() to accept the connection (if someone tries to connect).
In case you've previously configured your server socket with setSoTimeout(), there's a change that accept() will throw SocketTimeoutException because nobody tried to connect in a specified period of time. That's fine, server socket is still usable, so you just call accept() once again.
But SocketTimeoutException is not the only thing that accept() may throw. What does all the other exceptions mean? If I wrap call to accept() with 2 catch clauses: for SocketTimeoutException and IOException, can I still safely use the related ServerSocket instance after I got into IOException clause?
I'd really appreciate both Java-wide and ServerSocket-specific answers.
It is not safe to reuse the object. For such a question I would always look into a source, that is the reason it is open.
So if you look into that one: http://kickjava.com/src/java/net/ServerSocket.java.htm you notice that in accept() a SocketException (inherits from IOException) is thrown if the socket is closed or not bound anymore. Both states indicate that the ServerSocket is not valid anymore.
So for this class, generally, if you fail with an exception, always try to gracefully close the ServerSocket in a finally block and then recreate it.
Additionally on your Java-wide question scope: Always look into the source and understand what the interface is doing. If it is mission-critical write tests that reproduce the behaviour (should not be easy at all with such a low-level api).
Finally - is Java consistently doing such things that way? No. Some classes are stateless, others are not (like ServerSocket), some are thread-safe, others not. And you need to understand - either from the documentation or (mostly) from the code - what state they build in order to understand what to do when an Exception knocks you off from the main path.
Most people curse those checked Java exceptions, because most of them (as with most of the IOExceptions) are not really recoverable in a meaningful way. Most of the time, they argue, you cannot understand each and every fine corner case. Which is the reason why many complex frameworks may retry twice or thrice if they think in this case they might, but finally throw a RuntimeException to a top framework layer. There they make something useful out of it (a meaningful error providing context) and log all the details they have, which is a huge stack trace most of the time. A great resource of knowledge, feared by many developers.
So what can you do if you could not recover from an untested corner-case problem? Throw up (probably with a some subclass of RuntimeException) the most meaningful stacktrace annotated with all the context you have. Setup monitoring. And if you run into a frequent problem, fix it.
Yes. The object still exists - May be in an error state in which case it will throw other exceptions until that is rectified.
If you read the specification for ServerSocket, you will see that it throws an IOException "if an I/O error occurs when waiting for a connection." Is it safe to accept() on the socket again? Yes. Are you going to get the same Exception thrown again? Likely so.
I have not yet found an easy way to see if an object is still in a usable state. Each object makes its own rules.
In your specific case with ServerSocket I would try one of two different things:
Run netstat or some other utility to see what the OS thinks that the socket is doing. If the OS doesn't think it is listening, then something happened.
or
Write a test program that will throw the exception and see what it does. I do this all the time (especially with proprietary software). It would be harder in the ServerSocket case you picked, since all of the scenarios I can think of (e.g. address in use, insufficient privileges, etc.) would never result in an object being still valid.
But SocketTimeoutException is not the only thing that accept() may throw. What does all the other exceptions mean?
According to the javadoc, the declared exceptions are IOException, SecurityException, SocketTimeoutException and IllegalBlockingModeException. The SecurityException and IllegalBlockingModeException only occur in specific contexts and you should not attempt to catch and handle them. (They are not problems you want to try to recover from!) The IOException case occurs when "some other I/O error" occurs. The javadoc does not specify what those I/O errors might be, but possibilities might include such things as:
the address to which you have bound is no longer valid
a transport protocol error has occurred
some error (resource issue, bug ...) occurred in the OS protocol stack
(The fact that the javadoc doesn't say which IOException subclasses might be thrown is a hint that you shouldn't try to do clever things to try to recover. If you do, your code is likely to be platform dependent.)
If I wrap call to accept() with 2 catch clauses: for SocketTimeoutException and IOException, can I still safely use the related ServerSocket instance after I got into IOException clause?
Yes and no. It is safe in the sense that you won't put your application into a worse state than it is already in. On the other hand, there is no guarantee that the next accept call won't fail with the same problem.
If your application is intended to run as an unattended server, I don't think you have much choice but to log the IOException and try again ... hoping that the problem is transient.
You can find your answer to the javadoc of setsoTimeout, it says :
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a call to accept() for this ServerSocket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the ServerSocket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.

Wrapping try-catch that fetches from internet, in a while

So I have a try-catch statement in a java program that fetches things from the internet. How do I handle timeouts? Would I just wrap the try catch in a while statement and after some number of failed iterations tell the user to try later?
How do I handle timeouts? Would I just wrap the try catch in a while statement and after some number of failed iterations tell the user to try later?
I don't think that would be a good idea. IMO, the best thing to do is to pick a timeout that corresponds to the time that you think that the user should have to wait, and not use a loop. As #BalusC points out, any decent Http client API will give you a way to set the timeout before you make the request. Use it.
The problem with using a loop is that you are potentially adding load to an already overloaded server. Suppose that the real reason for the timeout is that the server is trying to handle too many requests in parallel, and each request is taking a long time. If you (the client) time out a request and then immediately retry it, you are probably just adding extra load ... making things worse.
The chances are that some users will hammer the retry button anyway. You don't need to do the hammering for them.

Categories