天天看點

一個詭異的 Pulsar InterruptedException 異常

作者:crossoverJie
一個詭異的 Pulsar InterruptedException 異常

背景

一個詭異的 Pulsar InterruptedException 異常

今天收到業務團隊回報線上有個應用往 Pulsar 中發送消息失敗了,經過日志檢視得知是發送消息時候抛出了 java.lang.InterruptedException 異常。

和業務溝通後得知是在一個 gRPC 接口中觸發的消息發送,大約持續了半個小時的異常後便恢複正常了,這是整個問題的背景。

前置排查

拿到該問題後首先排查下是否是共性問題,檢視了其他的應用沒有發現類似的異常;同時也檢視了 Pulsar broker 的監控大盤,在這個時間段依然沒有波動和異常;

這樣可以初步排除是 Pulsar 服務端的問題。

接着便是檢視應用那段時間的負載情況,從應用 QPS 到 JVM 的各個記憶體情況依然沒發現有什麼明顯的變化。

Pulsar 源碼排查

既然看起來應用本身和 Pulsar broker 都沒有問題的話那就隻能從異常本身來排查了。

首先第一步要得知具體使用的是 Pulsar-client 是版本是多少,因為業務使用的是内部基于官方 SDK 封裝 springboot starter 是以第一步還得排查這個 starter 是否有影響。

通過檢視源碼基本排除了 starter 的嫌疑,裡面隻是簡單的封裝了 SDK 的功能而已。

org.apache.pulsar.client.api.PulsarClientException: java.util.concurrent.ExecutionException: org.apache.pulsar.client.api.PulsarClientException: java.lang.InterruptedException at org.apache.pulsar.client.api.PulsarClientException.unwrap(PulsarClientException.java:1027) at org.apache.pulsar.client.impl.TypedMessageBuilderImpl.send(TypedMessageBuilderImpl.java:91) at 
java.base/java.lang.Thread.run(Thread.java:834) Caused by: java.util.concurrent.ExecutionException: org.apache.pulsar.client.api.PulsarClientException: java.lang.InterruptedException at java.base/java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:395) 
at java.base/java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1999) 
at org.apache.pulsar.client.impl.TypedMessageBuilderImpl.send(TypedMessageBuilderImpl.java:89) ... 49 common frames omitted Caused by: org.apache.pulsar.client.api.PulsarClientException: java.lang.InterruptedException 
at org.apache.pulsar.client.impl.ProducerImpl.canEnqueueRequest(ProducerImpl.java:775) 
at org.apache.pulsar.client.impl.ProducerImpl.sendAsync$original$BWm7PPlZ(ProducerImpl.java:393) 
at org.apache.pulsar.client.impl.ProducerImpl.sendAsync$original$BWm7PPlZ$accessor$i7NYMN6i(ProducerImpl.java) 
at org.apache.pulsar.client.impl.ProducerImpl$auxiliary$EfuVvJLT.call(Unknown Source) 
at org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstMethodsInter.intercept(InstMethodsInter.java:86) 
at org.apache.pulsar.client.impl.ProducerImpl.sendAsync(ProducerImpl.java) 
at org.apache.pulsar.client.impl.ProducerImpl.internalSendAsync(ProducerImpl.java:292) 
at org.apache.pulsar.client.impl.ProducerImpl.internalSendWithTxnAsync(ProducerImpl.java:363) 
at org.apache.pulsar.client.impl.PartitionedProducerImpl.internalSendWithTxnAsync(PartitionedProducerImpl.java:191) 
at org.apache.pulsar.client.impl.PartitionedProducerImpl.internalSendAsync(PartitionedProducerImpl.java:167) 
at org.apache.pulsar.client.impl.TypedMessageBuilderImpl.sendAsync(TypedMessageBuilderImpl.java:103) 
at org.apache.pulsar.client.impl.TypedMessageBuilderImpl.send(TypedMessageBuilderImpl.java:82) ... 49 common frames omitted Caused by: java.lang.InterruptedException: null
at java.base/java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1343) 
at java.base/java.util.concurrent.Semaphore.acquire(Semaphore.java:318) 
at org.apache.pulsar.client.impl.ProducerImpl.canEnqueueRequest(ProducerImpl.java:758)
           

接下來便隻能是分析堆棧了,因為 Pulsar-client 的部分實作源碼是沒有直接打包到依賴中的,反編譯的話許多代碼行數對不上,是以需要将官方的源碼拉到本地,切換到對于的分支進行檢視。

這一步稍微有點麻煩,首先是代碼庫還挺大的,加上之前如果沒有準備好 Pulsar 的開發環境的話估計會勸退一部分人;但其實大部分問題都是網絡造成的,隻要配置一些 Maven 鏡像多試幾次總會編譯成功。

我這裡直接将分支切換到 branch-2.8。

從堆棧的頂部開始排查 TypedMessageBuilderImpl.java:91:

一個詭異的 Pulsar InterruptedException 異常

看起來是内部異步發送消息的時候抛了異常。

接着往下看到這裡:

java.lang.InterruptedException 
at org.apache.pulsar.client.impl.ProducerImpl.canEnqueueRequest(ProducerImpl.java:775) at
           
一個詭異的 Pulsar InterruptedException 異常

看起來是這裡沒錯,但是代碼行數明顯不對;因為 2.8 這個分支也是修複過幾個版本,是以中間有修改導緻代碼行數與最新代碼對不上也正常。

semaphore.get().acquire();
           

不過初步來看應該是這行代碼抛出的線程終端異常,這裡看起來隻有他最有可能了。

一個詭異的 Pulsar InterruptedException 異常

為了确認是否是真的是這行代碼,這個檔案再往前翻了幾個版本最終确認了就是這行代碼沒錯了。

我們點開java.util.concurrent.Semaphore#acquire()的源碼,

/**
     * <li>has its interrupted status set on entry to this method; or
     * <li>is {@linkplain Thread#interrupt interrupted} while waiting
     * for a permit,
     * </ul>
     * then {@link InterruptedException} is thrown and the current thread's
     * interrupted status is cleared.
     *
     * @throws InterruptedException if the current thread is interrupted
     */
    public void acquire() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }
    
    public final void acquireSharedInterruptibly(int arg)
        throws InterruptedException {
        if (Thread.interrupted() ||
            (tryAcquireShared(arg) < 0 &&
             acquire(null, arg, true, true, false, 0L) < 0))
            throw new InterruptedException();
    }    
           

通過源碼會發現 acquire() 函數确實會響應中斷,一旦檢測到目前線程被中斷後便會抛出 InterruptedException 異常。

定位問題

是以問題的原因基本确定了,就是在 Pulsar 的發送消息線程被中斷了導緻的,但為啥會被中斷還需要繼續排查。

我們知道線程中斷是需要調用 Thread.currentThread().interrupt(); API的,首先猜測是否 Pulsar 用戶端内部有個線程中斷了這個發送線程。

于是我在 pulsar-client 這個子產品中搜尋了相關代碼:

一個詭異的 Pulsar InterruptedException 異常

排除掉和 producer 不相關的地方,其餘所有中斷線程的代碼都是在有了該異常之後繼續傳遞而已;是以初步來看 pulsar-client 内部沒有主動中斷的操作。

既然 Pulsar 自己沒有做,那就隻可能是業務做的了?

于是我在業務代碼中搜尋了一下:

一個詭異的 Pulsar InterruptedException 異常

果然在業務代碼中搜到了唯一一處中斷的地方,而且通過調用關系得知這段代碼是在消息發送前執行的,并且和 Pulsar 發送函數處于同一線程。

大概的僞代碼如下:

List.of(1, 2, 3).stream().map(e -> {
                    return CompletableFuture.supplyAsync(() -> {
                        try {
                            TimeUnit.MILLISECONDS.sleep(10);
                        } catch (InterruptedException ex) {
                            throw new RuntimeException(ex);
                        }
                        return e;
                    });
                }
        ).collect(Collectors.toList()).forEach(f -> {
            try {
                Integer integer = f.get();
                log.info("====" + integer);
                if (integer==3){
                    TimeUnit.SECONDS.sleep(10);
                    Thread.currentThread().interrupt();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            }
        });
    MessageId send = producer.newMessage().value(msg.getBytes()).send();
           

執行這段代碼可以完全複現同樣的堆棧。

幸好中斷這裡還打得有日志:

一個詭異的 Pulsar InterruptedException 異常
一個詭異的 Pulsar InterruptedException 異常

通過日志搜尋發現異常的時間和這個中斷的日志時間點完全重合,這樣也就知道根本原因了。

因為業務線程和消息發送線程是同一個,在某些情況下會執行 Thread.currentThread().interrupt();,其實單純執行這行函數并不會發生什麼,隻要沒有去響應這個中斷,也就是 Semaphore 源碼中的判斷了線程中斷的标記:

public final void acquireSharedInterruptibly(int arg)
        throws InterruptedException {
        if (Thread.interrupted() ||
            (tryAcquireShared(arg) < 0 &&
             acquire(null, arg, true, true, false, 0L) < 0))
            throw new InterruptedException();
    }
           

但恰好這裡業務中斷後自己并沒有去判斷這個标記,導緻 Pulsar 内部去判斷了,最終抛出了這個異常。

總結

是以歸根結底還是這裡的代碼不合理導緻的,首先是自己中斷了線程但也沒使用,進而導緻有被其他基礎庫使用的可能,是以會造成了一些不可預知的後果。

再一個是不建議在業務代碼中使用 Thread.currentThread().interrupt(); 這類代碼,第一眼根本不知道是要幹啥,也不易維護。

其實本質上線程中斷也是線程間通信的一種手段,有這類需求完全可以換為内置的 BlockQueue 這類函數來實作。

繼續閱讀