OutOfMemoryError:WildFlyでWebSocketを使用する場合のダイレクトバッファメモリ

Aug 21 2020

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 [email protected]//org.xnio.BufferAllocator$2.allocate(BufferAllocator.java:57) at [email protected]//org.xnio.BufferAllocator$2.allocate(BufferAllocator.java:55)
    at [email protected]//org.xnio.ByteBufferSlicePool.allocateSlices(ByteBufferSlicePool.java:162)
    at [email protected]//org.xnio.ByteBufferSlicePool.allocate(ByteBufferSlicePool.java:149)
    at [email protected]//io.undertow.server.XnioByteBufferPool.allocate(XnioByteBufferPool.java:53)
    at [email protected]//io.undertow.server.protocol.framed.AbstractFramedChannel.allocateReferenceCountedBuffer(AbstractFramedChannel.java:549)
    at [email protected]//io.undertow.server.protocol.framed.AbstractFramedChannel.receive(AbstractFramedChannel.java:370)
    at [email protected]//io.undertow.websockets.core.AbstractReceiveListener.handleEvent(AbstractReceiveListener.java:38)
    at [email protected]//io.undertow.websockets.core.AbstractReceiveListener.handleEvent(AbstractReceiveListener.java:33)
    at [email protected]//org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92)
    at [email protected]//io.undertow.server.protocol.framed.AbstractFramedChannel$FrameReadListener.handleEvent(AbstractFramedChannel.java:950) at [email protected]//io.undertow.server.protocol.framed.AbstractFramedChannel$FrameReadListener.handleEvent(AbstractFramedChannel.java:931)
    at [email protected]//org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92)
    at [email protected]//org.xnio.conduits.ReadReadyHandler$ChannelListenerHandler.readReady(ReadReadyHandler.java:66)
    at [email protected]//org.xnio.nio.NioSocketConduit.handleReady(NioSocketConduit.java:89)
    at [email protected]//org.xnio.nio.WorkerThread.run(WorkerThread.java:591)

jxrayを介してJVMダンプを確認しましたが、WebSocketが原因のようです。

事実は、私たちの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が開閉し、メッセージがほとんど送信されないことです。

どこでそれを間違え、このバッファリークを引き起こす可能性がありますか?重要なことを忘れましたか?

回答

CyrilG. Aug 30 2020 at 22:17

この投稿を見ると、CPUがたくさんある場合にこれが発生する可能性があります。これは、IOワーカーの数を減らすことで解決されました。これがあなたのケースに役立つかどうかはわかりません。