首頁 > 軟體

解決java啟動時報執行緒佔用報錯:Exception in thread 「Thread-14「 java.net.BindException: Address already in use: bi

2023-09-06 22:00:07

前言

本文提供三種不同的解決方式,也是三種不同的情況和思路

我的問題是在springboot整合了xxl-job一段時間後出現的。如果你程式裡整合了xxl-job或者有需要設定其它埠的地方,這篇文章或許可以給你帶來啟發或者解決你的問題。

1 異常

啟動專案後丟擲異常,但是奇怪的是執行器在任務排程中心中註冊成功,也能成功執行

  .   ____          _            __ _ _
 /\ / ___'_ __ _ _(_)_ __  __ _    
( ( )___ | '_ | '_| | '_ / _` |    
 \/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |___, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.2.RELEASE)

2023-02-14 11:22:15.516  INFO 4436 --- [           main] com.jxj.SafetyWebserverApplication       : Starting SafetyWebserverApplication on abc with PID 4436 (C:projectsafetyproduction_collectdatatargetclasses started by whx in C:projectsafetyproduction_collectdata)
2023-02-14 11:22:15.521  INFO 4436 --- [           main] com.jxj.SafetyWebserverApplication       : No active profile set, falling back to default profiles: default
2023-02-14 11:22:16.722  INFO 4436 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
....

2023-02-14 11:22:19.191  INFO 4436 --- [           main] o.s.s.c.ThreadPoolTaskScheduler          : Initializing ExecutorService 'taskScheduler'
2023-02-14 11:22:19.394  INFO 4436 --- [           main] com.jxj.config.XxlJobConfig              : >>>>>>>>>>> xxl-job config init.
2023-02-14 11:22:19.666  INFO 4436 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2023-02-14 11:22:20.271  INFO 4436 --- [           main] c.xxl.job.core.executor.XxlJobExecutor   : >>>>>>>>>>> xxl-job register jobhandler success, name:demoJobHandler, jobHandler:com.xxl.job.core.handler.impl.MethodJobHandler@c6bf8d9[class com.jxj.task.WarningTask#demoJobHandler]
2023-02-14 11:22:20.585  INFO 4436 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2023-02-14 11:22:20.586  INFO 4436 --- [           main] o.s.i.channel.PublishSubscribeChannel    : Channel 'application.errorChannel' has 1 subscriber(s).
2023-02-14 11:22:20.586  INFO 4436 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started bean '_org.springframework.integration.errorLogger'
2023-02-14 11:22:20.586  INFO 4436 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Adding {message-handler:mqttPublisherConfig.mqttOutbound.serviceActivator} as a subscriber to the 'mqttOutboundChannel' channel
2023-02-14 11:22:20.586  INFO 4436 --- [           main] o.s.integration.channel.DirectChannel    : Channel 'application.mqttOutboundChannel' has 1 subscriber(s).
2023-02-14 11:22:20.600  INFO 4436 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started bean 'mqttPublisherConfig.mqttOutbound.serviceActivator'
2023-02-14 11:22:20.600  INFO 4436 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Adding {message-handler:mqttSenderConfig.mqttOutbound.serviceActivator} as a subscriber to the 'mqttOutboundChannel1' channel
2023-02-14 11:22:20.601  INFO 4436 --- [           main] o.s.integration.channel.DirectChannel    : Channel 'application.mqttOutboundChannel1' has 1 subscriber(s).
2023-02-14 11:22:20.601  INFO 4436 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started bean 'mqttSenderConfig.mqttOutbound.serviceActivator'
2023-02-14 11:22:20.601  INFO 4436 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Adding {message-handler:mqttSubscriberConfig.handler.serviceActivator} as a subscriber to the 'mqttInboundChannel' channel
2023-02-14 11:22:20.601  INFO 4436 --- [           main] o.s.integration.channel.DirectChannel    : Channel 'application.mqttInboundChannel' has 1 subscriber(s).
2023-02-14 11:22:20.601  INFO 4436 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started bean 'mqttSubscriberConfig.handler.serviceActivator'
2023-02-14 11:22:20.601  INFO 4436 --- [           main] ProxyFactoryBean$MethodInvocationGateway : started bean 'mqttGateway'
2023-02-14 11:22:20.601  INFO 4436 --- [           main] ProxyFactoryBean$MethodInvocationGateway : started bean 'mqttGateway'
2023-02-14 11:22:20.601  INFO 4436 --- [           main] ProxyFactoryBean$MethodInvocationGateway : started bean 'mqttGateway'
2023-02-14 11:22:20.601  INFO 4436 --- [           main] o.s.i.gateway.GatewayProxyFactoryBean    : started bean 'mqttGateway'
Exception in thread "Thread-17" java.net.BindException: Address already in use: bind
	at sun.nio.ch.Net.bind0(Native Method)
	at sun.nio.ch.Net.bind(Net.java:433)
	at sun.nio.ch.Net.bind(Net.java:425)
	at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
	at io.netty.channel.socket.nio.NioServerSocketChannel.doBind(NioServerSocketChannel.java:134)
	at io.netty.channel.AbstractChannel$AbstractUnsafe.bind(AbstractChannel.java:551)
	at io.netty.channel.DefaultChannelPipeline$HeadContext.bind(DefaultChannelPipeline.java:1346)
	at io.netty.channel.AbstractChannelHandlerContext.invokeBind(AbstractChannelHandlerContext.java:503)
	at io.netty.channel.AbstractChannelHandlerContext.bind(AbstractChannelHandlerContext.java:488)
	at io.netty.channel.DefaultChannelPipeline.bind(DefaultChannelPipeline.java:985)
	at io.netty.channel.AbstractChannel.bind(AbstractChannel.java:247)
	at io.netty.bootstrap.AbstractBootstrap$2.run(AbstractBootstrap.java:344)
	at io.netty.util.concurrent.AbstractEventExecutor.safeExecute$$$capture(AbstractEventExecutor.java:163)
	at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java)
	at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:510)
	at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:518)
	at io.netty.util.concurrent.SingleThreadEventExecutor$6.run(SingleThreadEventExecutor.java:1050)
	at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
	at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
	at java.lang.Thread.run(Thread.java:748)
2023-02-14 11:22:21.444  INFO 4436 --- [           main] .m.i.MqttPahoMessageDrivenChannelAdapter : started bean 'inbound'; defined in: 'class path resource [com/jxj/config/MqttSubscriberConfig.class]'; from source: 'org.springframework.core.type.classreading.SimpleMethodMetadata@1d4664d7'
2023-02-14 11:22:21.446  INFO 4436 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [localhost:5672]
2023-02-14 11:22:25.537  INFO 4436 --- [           main] o.s.a.r.l.SimpleMessageListenerContainer : Broker not available; cannot force queue declarations during start: java.net.ConnectException: Connection refused: connect
2023-02-14 11:22:25.545  INFO 4436 --- [ntContainer#0-1] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [localhost:5672]

2 問題定位

2.1 第一種情況

網上有的說通過

在低版本的 xxl-job 中, 初始化XxlJobSpringExecutor執行器需要在@Bean中加上 initMethod = "start", destroyMethod = "destroy",但是在高版本的 xxl-job(如 2.1.2)則需要刪除 initMethod = "start", destroyMethod = "destroy"

而我的問題不是在bean上加(initMethod = “start”, destroyMethod = “destroy”),我加上之後會報兩遍執行緒被使用的異常。

Exception in thread "Thread-14" java.net.BindException: Address already in use: bind
	at sun.nio.ch.Net.bind0(Native Method)
	at sun.nio.ch.Net.bind(Net.java:433)
	at sun.nio.ch.Net.bind(Net.java:425)
	at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
	at io.netty.channel.socket.nio.NioServerSocketChannel.doBind(NioServerSocketChannel.java:134)
	at io.netty.channel.AbstractChannel$AbstractUnsafe.bind(AbstractChannel.java:551)
	at io.netty.channel.DefaultChannelPipeline$HeadContext.bind(DefaultChannelPipeline.java:1346)
	at io.netty.channel.AbstractChannelHandlerContext.invokeBind(AbstractChannelHandlerContext.java:503)
	at io.netty.channel.AbstractChannelHandlerContext.bind(AbstractChannelHandlerContext.java:488)
	at io.netty.channel.DefaultChannelPipeline.bind(DefaultChannelPipeline.java:985)
	at io.netty.channel.AbstractChannel.bind(AbstractChannel.java:247)
	at io.netty.bootstrap.AbstractBootstrap$2.run(AbstractBootstrap.java:344)
	at io.netty.util.concurrent.AbstractEventExecutor.safeExecute$$$capture(AbstractEventExecutor.java:163)
	at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java)
	at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:510)
	at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:518)
	at io.netty.util.concurrent.SingleThreadEventExecutor$6.run(SingleThreadEventExecutor.java:1050)
	at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
	at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
	at java.lang.Thread.run(Thread.java:748)
2023-02-14 11:25:20.568  INFO 18140 --- [           main] c.xxl.job.core.executor.XxlJobExecutor   : >>>>>>>>>>> xxl-job register jobhandler success, name:demoJobHandler, jobHandler:com.xxl.job.core.handler.impl.MethodJobHandler@1618c98a[class com.jxj.task.WarningTask#demoJobHandler]
Exception in thread "Thread-20" java.net.BindException: Address already in use: bind
	at sun.nio.ch.Net.bind0(Native Method)
	at sun.nio.ch.Net.bind(Net.java:433)
	at sun.nio.ch.Net.bind(Net.java:425)
	at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
	at io.netty.channel.socket.nio.NioServerSocketChannel.doBind(NioServerSocketChannel.java:134)
	at io.netty.channel.AbstractChannel$AbstractUnsafe.bind(AbstractChannel.java:551)
	at io.netty.channel.DefaultChannelPipeline$HeadContext.bind(DefaultChannelPipeline.java:1346)
	at io.netty.channel.AbstractChannelHandlerContext.invokeBind(AbstractChannelHandlerContext.java:503)
	at io.netty.channel.AbstractChannelHandlerContext.bind(AbstractChannelHandlerContext.java:488)
	at io.netty.channel.DefaultChannelPipeline.bind(DefaultChannelPipeline.java:985)
	at io.netty.channel.AbstractChannel.bind(AbstractChannel.java:247)
	at io.netty.bootstrap.AbstractBootstrap$2.run(AbstractBootstrap.java:344)
	at io.netty.util.concurrent.AbstractEventExecutor.safeExecute$$$capture(AbstractEventExecutor.java:163)
	at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java)
	at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:510)
	at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:518)
	at io.netty.util.concurrent.SingleThreadEventExecutor$6.run(SingleThreadEventExecutor.java:1050)
	at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
	at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
	at java.lang.Thread.run(Thread.java:748)
//原註解:
@Bean
public XxlJobSpringExecutor xxlJobExecutor() {
	...
	}
	
//修改後註解
@Bean(initMethod = "start", destroyMethod = "destroy")
public XxlJobSpringExecutor xxlJobExecutor() {
	...
	}

2.2 第二種情況

後來我發現我的問題是 本地和線上的程式連線了相同的xxl-job,並且連線xxl-job的埠是一樣的,導致了這個問題!

xxl:
  job:
    accessToken: xxx
    admin:
#       addresses: http://1xxxxx/xxl-job-admin
      addresses: http://39xxxxx/xxl-job-admin
    executor:
      address: 'xxx'
      appname: safexxxxxst #這個名字要和頁面設定的一致
      ip: ''
      logpath: /datxxxxjob/joxxxler
      logretentiondays: 30
      port: 9996

就是這個 port埠重複導致的問題修改一下即可

port: 9996

2.3 第三種情況

本來我是第二種情況已經解決了,結果下午又報這個錯了,因此有了第三種情況的解決。

啟動報錯時的 錯誤關鍵紀錄檔:

2023-02-14 13:59:12.074  INFO 8364 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Created new connection: rabbitConnectionFactory#131ba005:0/SimpleConnection@5981f2c6 [delegate=amqp://[email protected]:5673/, localPort= 5415]
Exception in thread "Thread-21" java.net.BindException: Address already in use: bind
	at sun.nio.ch.Net.bind0(Native Method)
	at sun.nio.ch.Net.bind(Net.java:433)
	at sun.nio.ch.Net.bind(Net.java:425)
	at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
	at io.netty.channel.socket.nio.NioServerSocketChannel.doBind(NioServerSocketChannel.java:134)
	at io.netty.channel.AbstractChannel$AbstractUnsafe.bind(AbstractChannel.java:551)
	at io.netty.channel.DefaultChannelPipeline$HeadContext.bind(DefaultChannelPipeline.java:1346)
	at io.netty.channel.AbstractChannelHandlerContext.invokeBind(AbstractChannelHandlerContext.java:503)
	at io.netty.channel.AbstractChannelHandlerContext.bind(AbstractChannelHandlerContext.java:488)
	at io.netty.channel.DefaultChannelPipeline.bind(DefaultChannelPipeline.java:985)
	at io.netty.channel.AbstractChannel.bind(AbstractChannel.java:247)
	at io.netty.bootstrap.AbstractBootstrap$2.run(AbstractBootstrap.java:344)
	at 

由於我已經解決過一次,所以我對埠比較敏感(大家看完後面的分析就可以知道我為什麼敏感),就在yaml檔案種搜了一下所有的 port 一共有五處。

排除專案的port(專案的介面衝突會直接報錯,停止執行

排除xxl-job (第二種情況衝突已經解決

剩下的是整合的 redis,elasticsearch,rabbitmq

redis和elasticsearch我都沒有開啟,問題就只在rabbitmq了。

rabbitmq我是本地起的docker,來連線測試的。

然後我有認真看了一下紀錄檔,就是上面貼出來的第一行

[delegate=amqp://[email protected]:5673/, localPort= 5415]

也就是列印完這個紀錄檔後報的錯誤,localPort= 5415,於是我又在本地檢視了一下這個5415埠使用情況

netstat -aon|findstr 5415

果然 兩個不同的執行緒在用!

C:Uxxxs1xx0>netstat -aon|findstr 5415
  TCP    127.0.0.1:5415         127.0.0.1:5673         ESTABLISHED     8364
  TCP    127.0.0.1:5673         127.0.0.1:5415         ESTABLISHED     4136

然後我開啟工作管理員 詳細資訊,找到4136是daocker

我重啟了一下電腦,,解決了

3 問題原因

程式啟動之後重新啟動了一個執行緒去連線xxl-job的埠,但是這個埠已經被佔用了,所以程式就直接返回了一個這個執行緒被佔用了。

4 思考學習

服務建立監聽的時候,如果埠有LISTENING、ESTABLISHED、TIME_WAIT等,好像都會報錯。 可以研究下原理

TCP狀態轉移要點

TCP協定規定,對於已經建立的連線,網路雙方要進行四次握手才能成功斷開連線,如果缺少了其中某個步驟,將會使連線處於假死狀態,連線本身佔用的資源不會被釋放。網路伺服器程式要同時管理大量連線,所以很有必要保證無用連線完全斷開,否則大量僵死的連線會浪費許多伺服器資源。在眾多TCP狀態中,最值得注意的狀態有兩個:CLOSE_WAIT和TIME_WAIT。

1、LISTENING狀態

  FTP服務啟動後首先處於偵聽(LISTENING)狀態。

2、ESTABLISHED狀態

  ESTABLISHED的意思是建立連線。表示兩臺機器正在通訊。

3、TIME_WAIT

我方主動呼叫close()斷開連線,收到對方確認後狀態變為TIME_WAIT。TCP協定規定TIME_WAIT狀態會一直持續2MSL(即兩倍的分段最大生存期),以此來確保舊的連線狀態不會對新連線產生影響。處於TIME_WAIT狀態的連線佔用的資源不會被核心釋放,所以作為伺服器,在可能的情況下,儘量不要主動斷開連線,以減少TIME_WAIT狀態造成的資源浪費。

目前有一種避免TIME_WAIT資源浪費的方法,就是關閉socket的LINGER選項。但這種做法是TCP協定不推薦使用的,在某些情況下這個操作可能會帶來錯誤。

總結

到此這篇關於解決java啟動時報執行緒佔用:Exception in thread “Thread-14“ java.net.BindException: Address already in use: bind的文章就介紹到這了,更多相關java啟動時報執行緒佔用內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com