java net sockettimeoutexception read timed out что делать
Java: socket read time out exception
I trying to make a call to a very heavy duty process. It’s average work length is estimated by 9-10 minutes.
When I’m executing the process, I set the timeout for a ridiculously huge number: 99999999.
After 2 minutes, I get the following error:
java.net.SocketTimeoutException: Read timed out
I tried to mess with it some more, and I set the timeout to 3000, and after 3 seconds as anticipated I got the same error.
Do you have any idea on why socket.setSoTimeout(99999999) sets it to 120000 max?
3 Answers 3
I had the same problem and the solution was not use socket.shutdownInput(); socket.shutDownOutput(); until the last time of reading or writing data to the socket. This made the socket go to FIN_WAIT state thus waiting 2 minutes before closing. You can read more about it in this post
Clearly you aren’t setting the timeout you think you’re setting, or someone else is changing it afterwards. You’ll have to post some code to get further elucidation.
Note that according to W.R. Stevens in TCP/IP Illustrated, Vol II, #17.4, the timeout is held in a short as a number of 1000Hz ticks, so a timeout beyond 11 minutes isn’t possible. This applies to the BSD code.
I’m not sure how your application works, but try to set an infinite timeout to the socket
If you provide more information about your call, i may improve the answer.
Jira Software Support
Get started
Knowledge base
Products
Jira Software
Project and issue tracking
Jira Service Management
Service management and customer support
Jira Core
Manage any business project
Confluence
Bitbucket
Git code management
Resources
Documentation
Usage and admin help
Community
Answers, support, and inspiration
System Status
Cloud services health
Suggestions and bugs
Feature suggestions and bug reports
Marketplace
Billing and licensing
Frequently asked questions
Viewport
Confluence
java.net.SocketTimeoutException: Read timed while making a request to a remote server
Related content
Still need help?
The Atlassian Community is here for you.
Summary
When a Jira instance makes an HTTP request to a remote server, the request fails with a message similar to:
Environment
The issue may occur in any setup where one Jira instance makes an HTTP request to a remote server.
For example, Jira A makes a request to Jira B via the Jira to Jira Issue Copy.
Diagnosis
The request in the remote server succeeds but takes more than 10 seconds, which is the default socket timeout for the client.
Cause
The reason why the request in the remote server takes more than 10 seconds should be investigated and potentially fixed.
If the request legitimately takes more than 10 seconds, the default socket timeout of 10 seconds isn’t enough on the Apache client side.
Where should I start investigating SocketTimeoutException: Read timed out
Every now and then I see following stacktrace in the log in which, HttpClient socket times out trying to access text/script content from another server. My question is what config settings should I check for my J2EE app running on Weblogic, on Linux? I am specifically looking for the following.
and this is the stacktrace
I will be updating my question with the FINDINGS below.
3 Answers 3
Track 1
The server session timeout represents the amount of time the HttpSession will be retained in memory if the user has not accessed the server.
The socket timeout is the amount of time to keep the server socket open while data is being transferred back to the caller. This could even be the server is still processing and writing back data but it’s taking rather long and the client has just timed out waiting for it.
Some links suggest this default is 60 seconds but the javadocs dont say anything, in any case you can set this value to something like 120 seconds to see if it helps
I would change the SO_Timeout and try again
There are the recommended BEA parameters for NDD values which govern how long incoming connections are kept open and how many are queued and so on. On Solaris these are got by running
Can you check the Oracle docs for the equivalent commands on Linux, and what values they should be set at. On Solaris my experience is the defaults are not enough and they need to be upped to BEA (Oracle) recommendations
Track 3: Weblogic / External Access Logs
Have you enabled HTTP Access Logs on the server? Do these failed requests show up with any response byte size or do they show 0 response size? What error code or HTTP status code is returned?
Or perhaps these timed out ones are not recorded in the access logs at all?
С чего мне начать расследование SocketTimeoutException: тайм-аут чтения
Время от времени я вижу в журнале следующую трассировку стека, в которой сокет HttpClient пытается получить доступ к text/script с другого сервера. У меня вопрос, какие параметры конфигурации я должен проверить для моего приложения J2EE, работающего в Weblogic, в Linux? Я специально ищу следующее.
и это трассировка стека
Я буду обновлять свой вопрос, используя приведенные ниже ВЫВОДЫ.
3 ответа
Трек 1
Сервер session timeout представляет количество времени, которое HttpSession будет сохранен в памяти, если пользователь не получил доступ к серверу.
В некоторых ссылках указано, что это значение по умолчанию составляет 60 секунд, но javadocs ничего не говорит, в любом случае вы можете установить это значение примерно на 120 секунд, чтобы посмотреть, поможет ли это
Я бы изменил SO_Timeout и повторил попытку
Существуют рекомендуемые параметры BEA для значений NDD, которые определяют, как долго входящие соединения остаются открытыми, сколько в очереди и так далее. На Солярисе их можно получить, запустив
Можете ли вы проверить документы Oracle на наличие эквивалентных команд в Linux и определить, на какие значения они должны быть установлены. Что касается Solaris, то, по моему опыту, значений по умолчанию недостаточно, и их необходимо использовать в соответствии с рекомендациями BEA (Oracle)
Дорожка 3: журналы веб-логики /внешнего доступа
Включили ли вы протоколы HTTP-доступа на сервере? Эти неудавшиеся запросы отображаются с каким-либо размером байта ответа или они показывают 0 размеров ответа? Какой код ошибки или код статуса HTTP возвращается?
Или, возможно, эти тайм-ауты вообще не записываются в журналы доступа?
Обычно дампы потока помогают, но дампы потока должны быть взяты на сервере, который имеет проблему тайм-аута. Вы являетесь клиентом и успешно установили соединение, после чего оно истекает при чтении ответа. Итак, внешний сервер перегружен? Отсутствие потоков? Процессор высокий? Слишком много одновременных запросов?
Я обнаружил, что исключения SocketTimeoutException часто могут быть связаны с тем, что порт не открыт для связи или брандмауэр блокирует связь только с выбранных компьютеров.
В случае, если вы устраняете проблему, убедитесь, что вы также исследуете, существует ли межсетевой экран между двумя компьютерами, пытающимися установить связь, и если таковой имеется, убедитесь, что порты доступны для связи между ними.
Надеюсь, это поможет.
Вы должны расследовать
(b) почему сервер не отвечает в течение этого периода, если он должен (просмотреть журналы сервера),
(c) в противном случае, почему время ожидания установлено слишком коротким. Многие тайм-ауты установлены слишком короткими, например, несколько секунд. Они должны составлять приличную долю минуты, а если ожидаемое время отклика больше, удвоить или утроить ожидаемое время отклика.
Jsoup SocketTimeoutException Read timed out Connect timed out fix
Jsoup SocketTimeoutException read timed out, connect timed out example shows how to fix SocketTimeoutException while using Jsoup in Java. The example also shows how to set the timeout in Jsoup.
How to fix Jsoup java.net.SocketTimeoutException: Read timed out exception?
You may encounter “java.net.SocketTimeoutException: Read timed out” exception while using the Jsoup. Here is the program which gave me the exception.
The problem is the default Jsoup timeout which is 3 seconds. If you encounter the exception “java.net.SocketTimeoutException: Read timed out”, it means that time our program took to read the requested webpage was exceeded the default timeout time (3 seconds).
You need to increase the timeout Jsoup uses to fix the problem using timeout method of Connection class.
This method sets the connect and read timeout both. Please note that the timeout is in milliseconds.
How to fix Jsoup java.net.SocketTimeoutException: Connect timed out exception?
Another exception Jsoup may throw is “java.net.SocketTimeoutException: Connect timed out”. This exception means the time taken by our program to connect to the requested URL exceeded the timeout Jsoup uses.
Here is how to fix/resolve the “Connect time out” exception.
1) Make sure you are connected to the internet. Try to open the same URL in the browser and see if it opens the page.
2) Specify Jsoup connection time out before getting the document as given below.