From 5f3a628b0beaa371faa1164c2288173aa1ad35c6 Mon Sep 17 00:00:00 2001
From: johnnyv <johnnyv@apache.org>
Date: Sat, 4 May 2019 13:18:44 -0400
Subject: [PATCH] Backport DIRMINA-1095 from 2.1.X

---
 .../socket/nio/NioDatagramAcceptor.java       | 49 +++++++++++--------
 1 file changed, 28 insertions(+), 21 deletions(-)

diff --git a/mina-core/src/main/java/org/apache/mina/transport/socket/nio/NioDatagramAcceptor.java b/mina-core/src/main/java/org/apache/mina/transport/socket/nio/NioDatagramAcceptor.java
index 09c35e79a..2db6a0c03 100644
--- a/mina-core/src/main/java/org/apache/mina/transport/socket/nio/NioDatagramAcceptor.java
+++ b/mina-core/src/main/java/org/apache/mina/transport/socket/nio/NioDatagramAcceptor.java
@@ -258,27 +258,34 @@ private int registerHandles() {
     }
 
     private void processReadySessions(Set<SelectionKey> handles) {
-        Iterator<SelectionKey> iterator = handles.iterator();
-
-        while (iterator.hasNext()) {
-            SelectionKey key = iterator.next();
-            DatagramChannel handle = (DatagramChannel) key.channel();
-            iterator.remove();
-
-            try {
-                if (key.isValid() && key.isReadable()) {
-                    readHandle(handle);
-                }
-
-                if (key.isValid() && key.isWritable()) {
-                    for (IoSession session : getManagedSessions().values()) {
-                        scheduleFlush((NioSession) session);
-                    }
-                }
-            } catch (Exception e) {
-                ExceptionMonitor.getInstance().exceptionCaught(e);
-            }
-        }
+	final Iterator<SelectionKey> iterator = handles.iterator();
+
+	while (iterator.hasNext()) {
+	    try {
+		final SelectionKey key = iterator.next();
+		final DatagramChannel handle = (DatagramChannel) key.channel();
+
+		if (key.isValid()) {
+		    if (key.isReadable()) {
+			readHandle(handle);
+		    }
+
+		    if (key.isWritable()) {
+			for (IoSession session : getManagedSessions().values()) {
+			    final NioSession x = (NioSession) session;
+			    if (x.getChannel() == handle) {
+				scheduleFlush(x);
+			    }
+			}
+		    }
+		}
+
+	    } catch (Exception e) {
+		ExceptionMonitor.getInstance().exceptionCaught(e);
+	    } finally {
+		iterator.remove();
+	    }
+	}
     }
 
     private boolean scheduleFlush(NioSession session) {