OutOfMemoryError:在 WildFly 中使用 websocket 时直接缓冲内存

Posted

技术标签:

【中文标题】OutOfMemoryError:在 WildFly 中使用 websocket 时直接缓冲内存【英文标题】:OutOfMemoryError: Direct buffer memory when using websockets in WildFly 【发布时间】:2020-12-10 15:24:23 【问题描述】:

在我们的 WildFly 18 服务器上一段时间后,在生产中,我们遇到了这个错误:

[org.xnio.listener] (default I/O-1) XNIO001007: A channel event listener threw an exception: 
java.lang.OutOfMemoryError: Direct buffer memory
    at java.base/java.nio.Bits.reserveMemory(Bits.java:175)
    at java.base/java.nio.DirectByteBuffer.<init>(DirectByteBuffer.java:118)
    at java.base/java.nio.ByteBuffer.allocateDirect(ByteBuffer.java:317)
    at org.jboss.xnio@3.7.3.Final//org.xnio.BufferAllocator$2.allocate(BufferAllocator.java:57)
    at org.jboss.xnio@3.7.3.Final//org.xnio.BufferAllocator$2.allocate(BufferAllocator.java:55)
    at org.jboss.xnio@3.7.3.Final//org.xnio.ByteBufferSlicePool.allocateSlices(ByteBufferSlicePool.java:162)
    at org.jboss.xnio@3.7.3.Final//org.xnio.ByteBufferSlicePool.allocate(ByteBufferSlicePool.java:149)
    at io.undertow.core@2.0.27.Final//io.undertow.server.XnioByteBufferPool.allocate(XnioByteBufferPool.java:53)
    at io.undertow.core@2.0.27.Final//io.undertow.server.protocol.framed.AbstractFramedChannel.allocateReferenceCountedBuffer(AbstractFramedChannel.java:549)
    at io.undertow.core@2.0.27.Final//io.undertow.server.protocol.framed.AbstractFramedChannel.receive(AbstractFramedChannel.java:370)
    at io.undertow.core@2.0.27.Final//io.undertow.websockets.core.AbstractReceiveListener.handleEvent(AbstractReceiveListener.java:38)
    at io.undertow.core@2.0.27.Final//io.undertow.websockets.core.AbstractReceiveListener.handleEvent(AbstractReceiveListener.java:33)
    at org.jboss.xnio@3.7.3.Final//org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92)
    at io.undertow.core@2.0.27.Final//io.undertow.server.protocol.framed.AbstractFramedChannel$FrameReadListener.handleEvent(AbstractFramedChannel.java:950)
    at io.undertow.core@2.0.27.Final//io.undertow.server.protocol.framed.AbstractFramedChannel$FrameReadListener.handleEvent(AbstractFramedChannel.java:931)
    at org.jboss.xnio@3.7.3.Final//org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92)
    at org.jboss.xnio@3.7.3.Final//org.xnio.conduits.ReadReadyHandler$ChannelListenerHandler.readReady(ReadReadyHandler.java:66)
    at org.jboss.xnio.nio@3.7.3.Final//org.xnio.nio.NiosocketConduit.handleReady(NioSocketConduit.java:89)
    at org.jboss.xnio.nio@3.7.3.Final//org.xnio.nio.WorkerThread.run(WorkerThread.java:591)

我们通过 jxray 检查了 JVM 转储,似乎 websockets 是罪魁祸首:

事实上,我们的 websocket 有点简单:

@ApplicationScoped
@ServerEndpoint(value = "/ws/messenger/accountId")
public class MessengerSocket implements Serializable

    private static final long serialVersionUID = -3173234888004281582L;

    @Inject
    private Logger log;
    @Inject
    private MessengerHandler handler;

    @OnOpen
    public void onOpen(@PathParam("accountId") String accountId, Session session, EndpointConfig config)
    
        log.debug("Opening for ", accountId);
        handler.subscribeSocket(session, UUID.fromString(accountId));
    

    @OnClose
    public void onClose(@PathParam("accountId") String accountId, Session session, CloseReason closeReason)
    
        log.debug("Closing ", accountId);
        handler.unsubscribeSocket(session, UUID.fromString(accountId));
    

它与一个简单的处理程序相结合,管理用户会话的地图:

@ApplicationScoped
public class MessengerHandler

    @Inject
    private Logger log;

    // key: Account id
    private Map<UUID, AccountMessengerSessions> sessions;

    public void init()
    
        sessions = new ConcurrentHashMap<>();
    

    public void subscribeSocket(Session session, UUID accountId)
    
        // build and store the account messenger session if new
        AccountMessengerSessions messenger = sessions.getOrDefault(accountId, new AccountMessengerSessions(accountId));
        messenger.getWsSessions().add(session);
        sessions.putIfAbsent(accountId, messenger);
        log.debug(" has  messenger socket session(s) (one added)", messenger.getAccountId(), messenger.getWsSessions().size());
    

    /**
     * Unsubscribes the provided WebSocket from the Messenger.
     */
    public void unsubscribeSocket(Session session, UUID accountId)
    
        if (!sessions.containsKey(accountId))
        
            log.warn("Ignore unsubscription from  socket, as  is unknwon from messenger", session.getId(), accountId);
            return;
        
        AccountMessengerSessions messenger = sessions.get(accountId);
        messenger.getWsSessions().remove(session);
        log.debug(" has  messenger socket session(s) (one removed)", messenger.getAccountId(), messenger.getWsSessions().size());
        if (!messenger.getWsSessions().isEmpty())
        
            return;
        
        // no more socket sessions, fully remove
        sessions.remove(messenger.getAccountId());
    

客户端,我们在页面加载时调用了一些 javascript,同样,没什么花哨的:

var accountId = // some string found in DOM
var websocketUrl = "wss://" + window.location.host + "/ws/messenger/" + accountId;
var websocket = new WebSocket(websocketUrl);
websocket.onmessage = function (event) 
  var data = JSON.parse(event.data);
  // nothing fancy here...
;

我们的用户并没有大量使用 websocket(即时通讯工具)提供的功能,因此生产中真正发生的事情基本上是 websocket 在每个页面上打开和关闭,发送的消息很少。

我们会在哪里弄错并造成缓冲区泄漏?我们是否忘记了一些重要的事情?

【问题讨论】:

你确定 unsubscribe/onClose 被调用而对所有 WebSocket 闭包没有任何问题吗?您是否能够重新创建此问题,如果可以,这样做的步骤是什么?我有两个最初的嫌疑人 1. 取消订阅没有被调用,所以会话被累积了。 2.退订时,您不会留下一些残留物 正如@VinayKV 所提到的,您确定您的会话映射得到正确维护,并且您不只是建立越来越多的套接字吗?衡量这一点的“会话计数”指标会很有用。此外,这个线程有一些关于导致 onClose 不执行的旧版本代码的详细信息,可能值得研究 - ***.com/a/45434399/1538039 调用了 onClose() 和 unsubscribe() 方法,是的,并且日志正在结束,表明每个用户没有打开任何更多会话(“用户 123 有 0 个信使套接字会话(删除一个)”)。 你能重现这个问题吗?如果是,则监视内存以查看调用取消订阅时泄漏的位置。取消订阅套接字会话时看起来有些残留 抱歉,忘记了那部分。不,我无法重现该问题。我尝试使用 Gatling 场景产生大量流量,手动打开 websockets(因为 Gatling 不处理 javascript),并且没有发生泄漏。 【参考方案1】:

我们的 wildfly 18 也有类似的问题(wildfly 19 也有此问题)。它可能是由 Wildfly 中的 faulty xnio 库触发的。更新到wildfly 22(使用最新的xnio lib)后问题就消失了。

【讨论】:

【参考方案2】:

看看这个post,如果你有很多CPU,这可能会发生。这是通过减少 IO 工作人员的数量来解决的。不确定这对您的情况是否有帮助。

【讨论】:

以上是关于OutOfMemoryError:在 WildFly 中使用 websocket 时直接缓冲内存的主要内容,如果未能解决你的问题,请参考以下文章

“OutOfMemoryError”的其他原因?

java.lang.OutOfMemoryError:

OutOfMemoryError 崩溃 Android

OutOfMemoryError:在 WildFly 中使用 websocket 时直接缓冲内存

Java HSQLDB - 批量插入:OutOfMemoryError:超出 GC 开销限制

为啥由于 java.lang.OutOfMemoryError,Spark Streaming 在字符串解码时失败?