Exception java.net.SocketTimeoutException: Read timed out - java

I need to communicate with some web service. I've downloaded Apache CXF from https://cxf.apache.org/download.html and generated Java classes with command
wsdl2java.bat -encoding UTF-8 <url>
But when I'm trying to run a long request after about 30 seconds I get exception:
Caused by: javax.xml.ws.soap.SOAPFaultException: java.net.SocketTimeoutException: Read timed out
at org.apache.axis2.jaxws.marshaller.impl.alt.MethodMarshallerUtils.createSystemException(MethodMarshallerUtils.java:1326)
at org.apache.axis2.jaxws.marshaller.impl.alt.MethodMarshallerUtils.demarshalFaultResponse(MethodMarshallerUtils.java:1052)
at org.apache.axis2.jaxws.marshaller.impl.alt.DocLitBareMethodMarshaller.demarshalFaultResponse(DocLitBareMethodMarshaller.java:415)
at org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.getFaultResponse(JAXWSProxyHandler.java:580)
at org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.createResponse(JAXWSProxyHandler.java:523)
at org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.invokeSEIMethod(JAXWSProxyHandler.java:389)
at org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.invoke(JAXWSProxyHandler.java:174)
at com.sun.proxy.$Proxy718.loadLoanHistorySynch(Unknown Source)
... 55 more
Caused by: java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.net.SocketInputStream.read(SocketInputStream.java:170)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read(BufferedInputStream.java:265)
at org.apache.commons.httpclient.HttpParser.readRawLine(HttpParser.java:88)
at org.apache.commons.httpclient.HttpParser.readLine(HttpParser.java:124)
at org.apache.commons.httpclient.HttpParser.readLine(HttpParser.java:105)
at org.apache.commons.httpclient.HttpConnection.readLine(HttpConnection.java:1116)
at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.readLine(MultiThreadedHttpConnectionManager.java:1413)
at org.apache.commons.httpclient.HttpMethodBase.readStatusLine(HttpMethodBase.java:1973)
at org.apache.commons.httpclient.HttpMethodBase.readResponse(HttpMethodBase.java:1735)
at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1098)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:621)
at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:193)
at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:75)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:404)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:231)
at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:443)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:406)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
at org.apache.axis2.jaxws.core.controller.impl.AxisInvocationController.execute(AxisInvocationController.java:578)
at org.apache.axis2.jaxws.core.controller.impl.AxisInvocationController.doInvoke(AxisInvocationController.java:127)
at org.apache.axis2.jaxws.core.controller.impl.InvocationControllerImpl.invoke(InvocationControllerImpl.java:93)
at org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.invokeSEIMethod(JAXWSProxyHandler.java:376)
... 67 more
I tried to increase timeout with different parameters but nothing helped:
int timeout = 60 * 1000;
((BindingProvider)client).getRequestContext().put("javax.xml.ws.client.connectionTimeout", timeout);
((BindingProvider)client).getRequestContext().put("javax.xml.ws.client.receiveTimeout", timeout);
((BindingProvider)client).getRequestContext().put("com.sun.xml.internal.ws.request.timeout", timeout);
((BindingProvider)client).getRequestContext().put("com.sun.xml.internal.ws.connect.timeout", timeout);
((BindingProvider)client).getRequestContext().put("com.sun.xml.ws.request.timeout", timeout);
((BindingProvider)client).getRequestContext().put("com.sun.xml.ws.connect.timeout", timeout);
((BindingProvider)client).getRequestContext().put("timeout", timeout);
How can I increase request timeout?

The timeout is in milliseconds so:
60 * 1000 = 60000;
which is basically 60 seconds, I tried like this below and it worked for me.
HashMap<String, java.lang.Object> properties = new HashMap<>();
properties.put(HTTPConstants.HTTP_PROTOCOL_VERSION,
HTTPConstants.HEADER_PROTOCOL_10);
properties.put(HTTPConstants.SO_TIMEOUT, new java.lang.Integer(
360000));
ServiceStub._getServiceClient().getOptions()
.setProperties(properties);

Related

Redis PubSub: Connections timeout

Our subscription client connections keeps disconnecting with the following error.
at org.springframework.data.redis.connection.jedis.JedisExceptionConverter.convert(JedisExceptionConverter.java:47)
at org.springframework.data.redis.connection.jedis.JedisExceptionConverter.convert(JedisExceptionConverter.java:36)
at org.springframework.data.redis.PassThroughExceptionTranslationStrategy.translate(PassThroughExceptionTranslationStrategy.java:37)
at org.springframework.data.redis.FallbackExceptionTranslationStrategy.translate(FallbackExceptionTranslationStrategy.java:37)
at org.springframework.data.redis.connection.jedis.JedisConnection.convertJedisAccessException(JedisConnection.java:210)
at org.springframework.data.redis.connection.jedis.JedisConnection.subscribe(JedisConnection.java:2986)
at org.springframework.data.redis.listener.RedisMessageListenerContainer$SubscriptionTask.eventuallyPerformSubscription(RedisMessageListenerContainer.java:784)
at org.springframework.data.redis.listener.RedisMessageListenerContainer$SubscriptionTask.run(RedisMessageListenerContainer.java:740)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketException: Connection reset
at redis.clients.util.RedisInputStream.ensureFill(RedisInputStream.java:202)
at redis.clients.util.RedisInputStream.readByte(RedisInputStream.java:40)
at redis.clients.jedis.Protocol.process(Protocol.java:151)
at redis.clients.jedis.Protocol.read(Protocol.java:215)
at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:340)
at redis.clients.jedis.Connection.getRawObjectMultiBulkReply(Connection.java:285)
at redis.clients.jedis.BinaryJedisPubSub.process(BinaryJedisPubSub.java:87)
at redis.clients.jedis.BinaryJedisPubSub.proceed(BinaryJedisPubSub.java:82)
at redis.clients.jedis.BinaryJedis.subscribe(BinaryJedis.java:3070)
at org.springframework.data.redis.connection.jedis.JedisConnection.subscribe(JedisConnection.java:2983)
... 5 common frames omitted
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:210)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.net.SocketInputStream.read(SocketInputStream.java:127)
at redis.clients.util.RedisInputStream.ensureFill(RedisInputStream.java:196)
... 14 common frames omitted
]
For having permanent connections, we have configured 0 timeout in both client and server.
Redis Client:
poolConfig.setMaxTotal(10);
poolConfig.setMaxIdle(5);
poolConfig.setBlockWhenExhausted(true);
poolConfig.setMinIdle(2);
poolConfig.setTestOnBorrow(true);
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(HOST);
factory.setPort(PORT);
factory.setDatabase(Protocol.DEFAULT_DATABASE);
factory.setPoolConfig(poolConfig);
factory.setTimeout(0);
JedisShardInfo shardInfo = new JedisShardInfo(factory.getHostName(), factory.getPort(), 0);
factory.setShardInfo(shardInfo);
return factory;
Redis Server Config:
127.0.0.1:6379> CONFIG GET client-output-buffer-limit
1) "client-output-buffer-limit"
2) "normal 0 0 0 slave 268435456 67108864 60 pubsub 257949696 134217728 0"
Can someone please help?

Drive.Files.Create.execute() java.net.SocketTimeoutException

I am trying to upload file using Drive.Files.Create api. It ran well but suddenly getting SocketTimeOut Exception after 10-15 request.
drive = new Drive.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(
APPLICATION_NAME).build();
Drive.Files.Create insert = drive.files().create(fileMetadata, mediaContent);
insert.setUseContentAsIndexableText(true);
File f=insert.execute();
Exception StackTrace:
Exception in thread "main" java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.net.SocketInputStream.read(SocketInputStream.java:170)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
at sun.security.ssl.InputRecord.read(InputRecord.java:503)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:930)
at sun.security.ssl.AppInputStream.read(AppInputStream.java:105)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:704)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:647)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1536)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)
at com.google.api.client.http.javanet.NetHttpResponse.<init>(NetHttpResponse.java:37)
at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:94)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:981)
at com.google.api.client.googleapis.media.MediaHttpUploader.executeCurrentRequestWithoutGZip(MediaHttpUploader.java:545)
at com.google.api.client.googleapis.media.MediaHttpUploader.resumableUpload(MediaHttpUploader.java:417)
at com.google.api.client.googleapis.media.MediaHttpUploader.upload(MediaHttpUploader.java:336)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:427)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
at com.ob.pdfparser.MyClass.uploadFile(MyClass.java:42)
at com.ob.pdfparser.MyClass.main(MyClass.java:91)
Usage Limit:
Queries
requests/day 20 of 1,000,000,000
requests/100seconds/user 1,000
Any Idea??
Below thing worked
Drive drive = new Drive.Builder(this.httpTransport, this.jsonFactory, this.credential).setHttpRequestInitializer(new HttpRequestInitializer() {#Override
public void initialize(HttpRequest httpRequest) throws IOException {
credential.initialize(httpRequest);
httpRequest.setConnectTimeout(300 * 60000); // 300 minutes connect timeout
httpRequest.setReadTimeout(300 * 60000); // 300 minutes read timeout
}
}).setApplicationName("My Application").build();
SocketTimeoutException: Read timed out can be solved by defining a connection timeout or adjusting the timeout barrier so that it's more flexible on network delays. Other than that, you can also check what causes delays in your network because, as far as I know, this kind of error is a network connectivity issue and not a programming issue.
Complete explanation about this kind of error can be found in java.net.SocketTimeoutException – How to Solve SocketTimeoutException and this SO post - Getting java.net.SocketTimeoutException: Connection timed out in android might also help.

jdbc begin failed

I get this error randomly when the web service is accessed.It is difficult to replicate and once I refresh it everything functions as expected.
Caused by: org.hibernate.exception.JDBCConnectionException: could not execute query
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:97)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.loader.Loader.doList(Loader.java:2235)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129)
at org.hibernate.loader.Loader.list(Loader.java:2124)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:118)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1597)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:306)
at edu.asd.myproj.hibernate.adapter.CriteriaAdapter.list(CriteriaAdapter.java:380)
at edu.asd.myproj.DaoHibernateImpl.findByCriteria(DaoHibernateImpl.java:778)
at edu.asd.myproj.DaoHibernateImpl.findByCriteria(DaoHibernateImpl.java:765)
at edu.asd.myproj.DaoHibernateImpl.findByProperty(DaoHibernateImpl.java:361)
at edu.asd.myproj.ProfilesDaoImpl.count(ProfilesDaoImpl.java:81)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy27.count(Unknown Source)
at edu.asd.myproj.ResourceProfileLoaderNew.loadProfiles(ResourceProfileLoaderNew.java:66)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:297)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:250)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:144)
... 50 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was44323 seconds ago.The last packet sent successfully to the server was 44323 seconds ago, which is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1074)
at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3246)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1917)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2542)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1734)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1885)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:93)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1812)
at org.hibernate.loader.Loader.doQuery(Loader.java:697)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
at org.hibernate.loader.Loader.doList(Loader.java:2232)
... 79 more
Caused by: java.net.SocketException: Broken pipe
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123)
at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3227)
... 90 more
This is my hibernate.properties file
# Turn on for SQL debugging
hibernate.show_sql=true
# Generate schema?
hibernate.hbm2ddl.auto=validate
#============================================================
# C3P0 connection pool configuration
#============================================================
#changed to default values
c3p0.acquireIncrement=hibernate.c3p0.acquire_increment
c3p0.idleConnectionTestPeriod=hibernate.c3p0.idle_test_period
c3p0.initialPoolSize=10
c3p0.maxIdleTime=hibernate.c3p0.timeout
c3p0.maxPoolSize=hibernate.c3p0.max_size
c3p0.maxStatements=hibernate.c3p0.max_statements
c3p0.minPoolSize=hibernate.c3p0.min_size
c3p0.testConnectionsOnCheckout=hibernate.c3p0.validate
The error is seen randomly once and it takes a long time before it reappears.It goes away once refreshed.
Please send complete exception stack trace for more understanding of reader.
This exception occured usually when a DB Connection stale.
Stale means: connection killed by the server, but still considered alive by the pool. You need to configure connection testing in the connection. For this approach in C3P0 you have to using following configuration:
c3p0.testConnectionOnCheckin = true
testConnectionOnCheckout= true
and for more checking increase checkout timeout as following:
c3p0.checkoutTimeout = 0
and test another test options in C3P0 such as :
connectionTesterClassName
idleConnectionTestPeriod
automaticTestTable
preferredTestQuery
Another way for test is writing a sample code and connect to database by a JDBC pure codes.(by DriverManager and Connection and etc )

Java Client + SSL Socket Error when using two timers to connect to a server

Scenario
ssl client that has two classes. One to transact and another to send network messages.
They share the connect function.
If i run each separately, the connection is made and appropriate response received.
If i run them concurrently, the connection is made but errors like
Errorjava.io.UTFDataFormatException: malformed input around byte 135
socket timeouts occur
the system eventually freezes.
question
how can i run the network and transact messages concurrently without them clashing as they are?
// connect code
try {
secureRandom = new SecureRandom();
secureRandom.nextInt();
System.out.println("Done.. Initializing Random Numbers.....:-");
String host = getHost();
int port = getPort();
setupServerKeystore();
setupClientKeyStore();
setupSSLContext();
SSLSocketFactory sf = sslContext.getSocketFactory();
SSLSocket socket = (SSLSocket) sf.createSocket(host, port);
socket.setSoTimeout(10000);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
this.din = new DataInputStream(in);
this.dout = new DataOutputStream(out);
// snip
// Schedule the two timers to run with different delays.
pingTimer.schedule(new Ping("ping"), 0, pingdelay);
vendTimer.schedule(new Vend("vend"), 0, venddelay);
} // end main
// stacktrace
vend - Current time: 20.04.2012 12:04:28
ping - Current time: 20.04.2012 12:04:28
Incoming Errorjava.io.UTFDataFormatException: malformed input around byte 135
java.io.UTFDataFormatException: malformed input around byte 135
at java.io.DataInputStream.readUTF(DataInputStream.java:639)
at java.io.DataInputStream.readUTF(DataInputStream.java:547)
at timerexample.Ping.run(Ping.java:76)
at java.util.TimerThread.mainLoop(Timer.java:512)
at java.util.TimerThread.run(Timer.java:462)
=========== Connected is True
null
ping - Current time: 20.04.2012 12:04:30
Incoming Errorjava.net.SocketTimeoutException: Read timed out
java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:129)
at com.sun.net.ssl.internal.ssl.InputRecord.readFully(InputRecord.java:293)
at com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:331)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:789)
=========== Connected is True
null
vend - Current time: 20.04.2012 12:04:46
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:746)
at com.sun.net.ssl.internal.ssl.AppInputStream.read(AppInputStream.java:75)
at java.io.DataInputStream.readFully(DataInputStream.java:178)
at java.io.DataInputStream.readUTF(DataInputStream.java:592)
at java.io.DataInputStream.readUTF(DataInputStream.java:547)
at timerexample.Ping.run(Ping.java:76)
at java.util.TimerThread.mainLoop(Timer.java:512)
at java.util.TimerThread.run(Timer.java:462)
Incoming Errorjava.net.SocketTimeoutException: Read timed out
java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:129)
at com.sun.net.ssl.internal.ssl.InputRecord.readFully(InputRecord.java:293)
at com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:331)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:789)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:746)
at com.sun.net.ssl.internal.ssl.AppInputStream.read(AppInputStream.java:75)
at java.io.DataInputStream.readFully(DataInputStream.java:178)
at java.io.DataInputStream.readUTF(DataInputStream.java:592)
at java.io.DataInputStream.readUTF(DataInputStream.java:547)
at timerexample.Ping.run(Ping.java:76)
=========== Connected is True
null
ping - Current time: 20.04.2012 12:05:02
at java.util.TimerThread.mainLoop(Timer.java:512)
at java.util.TimerThread.run(Timer.java:462)
java.net.SocketTimeoutException: Read timed out
Incoming Errorjava.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:129)
at com.sun.net.ssl.internal.ssl.InputRecord.readFully(InputRecord.java:293)
at com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:331)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:789)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:746)
=========== Connected is True
null
ping - Current time: 20.04.2012 12:05:17
at com.sun.net.ssl.internal.ssl.AppInputStream.read(AppInputStream.java:75)
at com.sun.net.ssl.internal.ssl.AppInputStream.read(AppInputStream.java:50)
at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:320)
at java.io.DataInputStream.readUTF(DataInputStream.java:572)
at java.io.DataInputStream.readUTF(DataInputStream.java:547)
at timerexample.Ping.run(Ping.java:76)
at java.util.TimerThread.mainLoop(Timer.java:512)
at java.util.TimerThread.run(Timer.java:462)

Spring 2.5 Could not get JDBC Connection

I'm using spring 2.5 SimpleJdbcTemplate to access MySQL db. When I try to access the DB too often(using Quartz to access it every minute) i get this stack trace:
org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.)
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:82)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:382)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:458)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:466)
at org.springframework.jdbc.core.JdbcTemplate.queryForList(JdbcTemplate.java:497)
at org.springframework.jdbc.core.simple.SimpleJdbcTemplate.queryForList(SimpleJdbcTemplate.java:223)
at com.db.timexis.dao.UserDaoJdbc.getListOfAllUsers(UserDaoJdbc.java:137)
at com.db.timexis.service.AuthServiceImpl.getListOfAllUsers(AuthServiceImpl.java:77)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy0.getListOfAllUsers(Unknown Source)
at com.mail.timexis.ReminderBean.execute(ReminderBean.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.util.MethodInvoker.invoke(MethodInvoker.java:276)
at org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean$MethodInvokingJob.executeInternal(MethodInvokingJobDetailFactoryBean.java:260)
at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:86)
at org.quartz.core.JobRunShell.run(JobRunShell.java:216)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:549)
Caused by: org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.)
at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1225)
at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:880)
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:113)
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:79)
... 30 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1122)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2260)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:787)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:49)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:357)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at org.apache.commons.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38)
at org.apache.commons.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:294)
at org.apache.commons.dbcp.BasicDataSource.validateConnectionFactory(BasicDataSource.java:1247)
at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1221)
... 33 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The driver was unable to create a connection due to an inability to establish the client portion of a socket.
This is usually caused by a limit on the number of sockets imposed by the operating system. This limit is usually configurable.
For Unix-based platforms, see the manual page for the 'ulimit' command. Kernel or system reconfiguration may also be required.
For Windows-based platforms, see Microsoft Knowledge Base Article 196271 (Q196271).
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1122)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:344)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2181)
... 46 more
Caused by: java.net.BindException: Address already in use: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at java.net.Socket.<init>(Socket.java:366)
at java.net.Socket.<init>(Socket.java:209)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:293)
... 47 more
The code executed every minute:
public void execute() {
List<User> regularUsers = null;
try {
// get all regular users
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml");
AuthService authService = (AuthService) ctx.getBean("authService");
regularUsers = authService.getListOfAllUsers();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (regularUsers != null) {
for (User u : regularUsers) {
if (u.getEmail().matches("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[_A-Za-z0-9-]+)")) {
mailSender.sendMailReminder(u.getEmail(),
u.getFirstName());
// log mail sending
Date date = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy/MM/dd HH:mm:ss");
String strDate = sdf.format(date);
System.out.println(strDate + "Reminder mail send...");
// log mail sending
}else{
System.out.println("invalid mail address");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
It's executed every minute for testing purposes. It will be executed once a week in the future.
My DBCP propertyes:
jdbc.maxActive=15
jdbc.maxIdle=10
jdbc.minIdle=5
jdbc.maxWait=5000
jdbc.validationQuery=select 1
jdbc.timeBetweenEvictionRunsMillis=1000
jdbc.numTestsPerEvictionRun=10
jdbc.minEvictableIdleTimeMillis=1200000
The data base is accessable trough the command line.
Note that you create a new instance of application context each time your method is invoked, and don't close it. It means that resources allocated by beans decalred in this context (for example, connections created by connection pool) are not released.
Typically you need to create application context only once during startup of your application and close it upon shutdown, so I suggest you to implement it this way.
If you actullay need to create a new application context each time you call that method, don't forget to close() it at the end of the method (in finally block for reliability).
Also note that you should declare an appropriate destroy-method for your connection pool bean in order to release resources when context is being closed.
The main exception is "java.net.BindException: Address already in use: connect". It seems you have connection pool leak. Are you sure that every connection is closed after usage? Please check it.

Categories