From 5f5732d3b076b784cf72420bf918d5c91875aa40 Mon Sep 17 00:00:00 2001
From: "slav.babanin" <slav.babanin@mongodb.com>
Date: Mon, 14 Apr 2025 10:40:39 -0700
Subject: [PATCH 1/4] Replace Stack with ArrayDeque.

JAVA-5852
---
 .../src/main/org/bson/AbstractBsonWriter.java | 19 +++++++-------
 bson/src/main/org/bson/BsonBinaryWriter.java  | 15 ++++++-----
 .../connection/ByteBufBsonDocument.java       |  9 +++----
 .../internal/connection/CommandMessage.java   |  5 ++--
 .../ByteBufBsonDocumentSpecification.groovy   | 26 +++++++++++++++++++
 5 files changed, 50 insertions(+), 24 deletions(-)

diff --git a/bson/src/main/org/bson/AbstractBsonWriter.java b/bson/src/main/org/bson/AbstractBsonWriter.java
index 8a8b238e8af..d0ec8ffa4ed 100644
--- a/bson/src/main/org/bson/AbstractBsonWriter.java
+++ b/bson/src/main/org/bson/AbstractBsonWriter.java
@@ -20,10 +20,11 @@
 import org.bson.types.ObjectId;
 
 import java.io.Closeable;
+import java.util.ArrayDeque;
 import java.util.Arrays;
+import java.util.Deque;
 import java.util.List;
 import java.util.Map;
-import java.util.Stack;
 
 import static java.lang.String.format;
 import static org.bson.assertions.Assertions.notNull;
@@ -35,7 +36,7 @@
  */
 public abstract class AbstractBsonWriter implements BsonWriter, Closeable {
     private final BsonWriterSettings settings;
-    private final Stack<FieldNameValidator> fieldNameValidatorStack = new Stack<>();
+    private final Deque<FieldNameValidator> fieldNameValidatorQueue = new ArrayDeque<>();
     private State state;
     private Context context;
     private int serializationDepth;
@@ -61,7 +62,7 @@ protected AbstractBsonWriter(final BsonWriterSettings settings, final FieldNameV
             throw new IllegalArgumentException("Validator can not be null");
         }
         this.settings = settings;
-        fieldNameValidatorStack.push(validator);
+        fieldNameValidatorQueue.push(validator);
         state = State.INITIAL;
     }
 
@@ -276,8 +277,8 @@ public void writeStartDocument(final String name) {
     public void writeStartDocument() {
         checkPreconditions("writeStartDocument", State.INITIAL, State.VALUE, State.SCOPE_DOCUMENT, State.DONE);
         if (context != null && context.name != null) {
-            FieldNameValidator validator = fieldNameValidatorStack.peek().getValidatorForField(getName());
-            fieldNameValidatorStack.push(validator);
+            FieldNameValidator validator = fieldNameValidatorQueue.peek().getValidatorForField(getName());
+            fieldNameValidatorQueue.push(validator);
             validator.start();
         }
         serializationDepth++;
@@ -300,7 +301,7 @@ public void writeEndDocument() {
         }
 
         if (context.getParentContext() != null && context.getParentContext().name != null) {
-            fieldNameValidatorStack.pop().end();
+            fieldNameValidatorQueue.pop().end();
         }
         serializationDepth--;
 
@@ -324,7 +325,7 @@ public void writeStartArray() {
         checkPreconditions("writeStartArray", State.VALUE);
 
         if (context != null && context.name != null) {
-            fieldNameValidatorStack.push(fieldNameValidatorStack.peek().getValidatorForField(getName()));
+            fieldNameValidatorQueue.push(fieldNameValidatorQueue.peek().getValidatorForField(getName()));
         }
         serializationDepth++;
         if (serializationDepth > settings.getMaxSerializationDepth()) {
@@ -345,7 +346,7 @@ public void writeEndArray() {
         }
 
         if (context.getParentContext() != null && context.getParentContext().name != null) {
-            fieldNameValidatorStack.pop();
+            fieldNameValidatorQueue.pop();
         }
         serializationDepth--;
 
@@ -530,7 +531,7 @@ public void writeName(final String name) {
         if (state != State.NAME) {
             throwInvalidState("WriteName", State.NAME);
         }
-        FieldNameValidator fieldNameValidator = fieldNameValidatorStack.peek();
+        FieldNameValidator fieldNameValidator = fieldNameValidatorQueue.peek();
         if (!fieldNameValidator.validate(name)) {
             throw new IllegalArgumentException(fieldNameValidator.getValidationErrorMessage(name));
         }
diff --git a/bson/src/main/org/bson/BsonBinaryWriter.java b/bson/src/main/org/bson/BsonBinaryWriter.java
index 150bdaa8ee8..f6e6e436c09 100644
--- a/bson/src/main/org/bson/BsonBinaryWriter.java
+++ b/bson/src/main/org/bson/BsonBinaryWriter.java
@@ -21,8 +21,9 @@
 import org.bson.types.Decimal128;
 import org.bson.types.ObjectId;
 
+import java.util.ArrayDeque;
+import java.util.Deque;
 import java.util.List;
-import java.util.Stack;
 
 import static java.lang.Math.max;
 import static java.lang.String.format;
@@ -37,7 +38,7 @@ public class BsonBinaryWriter extends AbstractBsonWriter {
     private final BsonBinaryWriterSettings binaryWriterSettings;
 
     private final BsonOutput bsonOutput;
-    private final Stack<Integer> maxDocumentSizeStack = new Stack<>();
+    private final Deque<Integer> maxDocumentSizeQueue = new ArrayDeque<>();
     private static final int ARRAY_INDEXES_CACHE_SIZE = 1000;
     private static final byte[] ARRAY_INDEXES_BUFFER;
     private static final int[] ARRAY_INDEXES_OFFSETS;
@@ -113,7 +114,7 @@ public BsonBinaryWriter(final BsonWriterSettings settings, final BsonBinaryWrite
         super(settings, validator);
         this.binaryWriterSettings = binaryWriterSettings;
         this.bsonOutput = bsonOutput;
-        maxDocumentSizeStack.push(binaryWriterSettings.getMaxDocumentSize());
+        maxDocumentSizeQueue.push(binaryWriterSettings.getMaxDocumentSize());
     }
 
     @Override
@@ -394,14 +395,14 @@ private void pipeDocument(final BsonReader reader, final List<BsonElement> extra
      * @param maxDocumentSize the maximum document size.
      */
     public void pushMaxDocumentSize(final int maxDocumentSize) {
-        maxDocumentSizeStack.push(maxDocumentSize);
+        maxDocumentSizeQueue.push(maxDocumentSize);
     }
 
     /**
      * Reset the maximum document size to its previous value.
      */
     public void popMaxDocumentSize() {
-        maxDocumentSizeStack.pop();
+        maxDocumentSizeQueue.pop();
     }
 
     /**
@@ -447,9 +448,9 @@ private void backpatchSize() {
     }
 
     private void validateSize(final int size) {
-        if (size > maxDocumentSizeStack.peek()) {
+        if (size > maxDocumentSizeQueue.peek()) {
             throw new BsonMaximumSizeExceededException(format("Document size of %d is larger than maximum of %d.", size,
-                    maxDocumentSizeStack.peek()));
+                    maxDocumentSizeQueue.peek()));
         }
     }
 
diff --git a/driver-core/src/main/com/mongodb/internal/connection/ByteBufBsonDocument.java b/driver-core/src/main/com/mongodb/internal/connection/ByteBufBsonDocument.java
index 70ed10a75a8..e85eadde425 100644
--- a/driver-core/src/main/com/mongodb/internal/connection/ByteBufBsonDocument.java
+++ b/driver-core/src/main/com/mongodb/internal/connection/ByteBufBsonDocument.java
@@ -17,6 +17,7 @@
 package com.mongodb.internal.connection;
 
 import com.mongodb.lang.Nullable;
+import org.bson.BsonArray;
 import org.bson.BsonBinaryReader;
 import org.bson.BsonDocument;
 import org.bson.BsonType;
@@ -36,10 +37,8 @@
 import java.util.AbstractCollection;
 import java.util.AbstractMap;
 import java.util.AbstractSet;
-import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Iterator;
-import java.util.List;
 import java.util.Map;
 import java.util.NoSuchElementException;
 import java.util.Set;
@@ -54,13 +53,13 @@ final class ByteBufBsonDocument extends BsonDocument {
     private final transient ByteBuf byteBuf;
 
     /**
-     * Create a list of ByteBufBsonDocument from a buffer positioned at the start of the first document of an OP_MSG Section
+     * Create a {@link BsonArray} of ByteBufBsonDocument from a buffer positioned at the start of the first document of an OP_MSG Section
      * of type Document Sequence (Kind 1).
      * <p>
      * The provided buffer will be positioned at the end of the section upon normal completion of the method
      */
-    static List<ByteBufBsonDocument> createList(final ByteBuf outputByteBuf) {
-        List<ByteBufBsonDocument> documents = new ArrayList<>();
+    static BsonArray createBsonArray(final ByteBuf outputByteBuf) {
+        BsonArray documents = new BsonArray();
         while (outputByteBuf.hasRemaining()) {
             ByteBufBsonDocument curDocument = createOne(outputByteBuf);
             documents.add(curDocument);
diff --git a/driver-core/src/main/com/mongodb/internal/connection/CommandMessage.java b/driver-core/src/main/com/mongodb/internal/connection/CommandMessage.java
index 12543e92ccb..f3a6a06a988 100644
--- a/driver-core/src/main/com/mongodb/internal/connection/CommandMessage.java
+++ b/driver-core/src/main/com/mongodb/internal/connection/CommandMessage.java
@@ -26,7 +26,6 @@
 import com.mongodb.internal.connection.MessageSequences.EmptyMessageSequences;
 import com.mongodb.internal.session.SessionContext;
 import com.mongodb.lang.Nullable;
-import org.bson.BsonArray;
 import org.bson.BsonBinaryWriter;
 import org.bson.BsonBoolean;
 import org.bson.BsonDocument;
@@ -57,7 +56,7 @@
 import static com.mongodb.internal.connection.BsonWriterHelper.backpatchLength;
 import static com.mongodb.internal.connection.BsonWriterHelper.writeDocumentsOfDualMessageSequences;
 import static com.mongodb.internal.connection.BsonWriterHelper.writePayload;
-import static com.mongodb.internal.connection.ByteBufBsonDocument.createList;
+import static com.mongodb.internal.connection.ByteBufBsonDocument.createBsonArray;
 import static com.mongodb.internal.connection.ByteBufBsonDocument.createOne;
 import static com.mongodb.internal.connection.ReadConcernHelper.getReadConcernDocument;
 import static com.mongodb.internal.operation.ServerVersionHelper.UNKNOWN_WIRE_VERSION;
@@ -168,7 +167,7 @@ BsonDocument getCommandDocument(final ByteBufferBsonOutput bsonOutput) {
 
                         ByteBuf documentsByteBufSlice = byteBuf.duplicate().limit(sectionEnd);
                         try {
-                            commandBsonDocument.append(fieldName, new BsonArray(createList(documentsByteBufSlice)));
+                            commandBsonDocument.append(fieldName, createBsonArray(documentsByteBufSlice));
                         } finally {
                             documentsByteBufSlice.release();
                         }
diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/ByteBufBsonDocumentSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/ByteBufBsonDocumentSpecification.groovy
index 8dc599706a9..63373b3756a 100644
--- a/driver-core/src/test/unit/com/mongodb/internal/connection/ByteBufBsonDocumentSpecification.groovy
+++ b/driver-core/src/test/unit/com/mongodb/internal/connection/ByteBufBsonDocumentSpecification.groovy
@@ -310,4 +310,30 @@ class ByteBufBsonDocumentSpecification extends Specification {
         }
     }
 
+    def "createBsonArray should create array of documents from BSON buffer"() {
+        given:
+        def bsonData = [
+                0x13, 0x00, 0x00, 0x00, // Document size (13 bytes)
+                0x10, 'a'.bytes[0], 0x00, 0x01, 0x00, 0x00, 0x00, // Int32 field "a" with value 1
+                0x10, 'b'.bytes[0], 0x00, 0x02, 0x00, 0x00, 0x00, // Int32 field "b" with value 2
+                0x00, // End of document
+
+                0x13, 0x00, 0x00, 0x00, // Document size (13 bytes)
+                0x10, 'c'.bytes[0], 0x00, 0x05, 0x00, 0x00, 0x00, // Int32 field "a" with value 5
+                0x10, 'd'.bytes[0], 0x00, 0x04, 0x00, 0x00, 0x00, // Int32 field "b" with value 4
+                0x00 // End of document
+        ] as byte[]
+        def byteBuf = new ByteBufNIO(ByteBuffer.wrap(bsonData))
+
+        when:
+        def result = ByteBufBsonDocument.createBsonArray(byteBuf)
+
+        then:
+        result.size() == 2
+        result[0].get("a") == new BsonInt32(1)
+        result[0].get("b") == new BsonInt32(2)
+
+        result[1].get("c") == new BsonInt32(5)
+        result[1].get("d") == new BsonInt32(4)
+    }
 }

From 7883749e878e3e7e0c7b5fda800d131bf7366b26 Mon Sep 17 00:00:00 2001
From: "slav.babanin" <slav.babanin@mongodb.com>
Date: Wed, 16 Apr 2025 15:21:52 -0700
Subject: [PATCH 2/4] Correct tests.

JAVA-5852
---
 .../connection/ByteBufBsonDocumentSpecification.groovy        | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/ByteBufBsonDocumentSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/ByteBufBsonDocumentSpecification.groovy
index 63373b3756a..f86ae0a16b5 100644
--- a/driver-core/src/test/unit/com/mongodb/internal/connection/ByteBufBsonDocumentSpecification.groovy
+++ b/driver-core/src/test/unit/com/mongodb/internal/connection/ByteBufBsonDocumentSpecification.groovy
@@ -319,8 +319,8 @@ class ByteBufBsonDocumentSpecification extends Specification {
                 0x00, // End of document
 
                 0x13, 0x00, 0x00, 0x00, // Document size (13 bytes)
-                0x10, 'c'.bytes[0], 0x00, 0x05, 0x00, 0x00, 0x00, // Int32 field "a" with value 5
-                0x10, 'd'.bytes[0], 0x00, 0x04, 0x00, 0x00, 0x00, // Int32 field "b" with value 4
+                0x10, 'c'.bytes[0], 0x00, 0x05, 0x00, 0x00, 0x00, // Int32 field "c" with value 5
+                0x10, 'd'.bytes[0], 0x00, 0x04, 0x00, 0x00, 0x00, // Int32 field "d" with value 4
                 0x00 // End of document
         ] as byte[]
         def byteBuf = new ByteBufNIO(ByteBuffer.wrap(bsonData))

From 160b168826df99a866861ca3b1afae7939c65773 Mon Sep 17 00:00:00 2001
From: "slav.babanin" <slav.babanin@mongodb.com>
Date: Wed, 16 Apr 2025 15:30:38 -0700
Subject: [PATCH 3/4] Remove CommandMessage optimization.

JAVA-5852
---
 .../connection/ByteBufBsonDocument.java       |  9 ++++---
 .../internal/connection/CommandMessage.java   |  5 ++--
 .../ByteBufBsonDocumentSpecification.groovy   | 26 -------------------
 3 files changed, 8 insertions(+), 32 deletions(-)

diff --git a/driver-core/src/main/com/mongodb/internal/connection/ByteBufBsonDocument.java b/driver-core/src/main/com/mongodb/internal/connection/ByteBufBsonDocument.java
index e85eadde425..70ed10a75a8 100644
--- a/driver-core/src/main/com/mongodb/internal/connection/ByteBufBsonDocument.java
+++ b/driver-core/src/main/com/mongodb/internal/connection/ByteBufBsonDocument.java
@@ -17,7 +17,6 @@
 package com.mongodb.internal.connection;
 
 import com.mongodb.lang.Nullable;
-import org.bson.BsonArray;
 import org.bson.BsonBinaryReader;
 import org.bson.BsonDocument;
 import org.bson.BsonType;
@@ -37,8 +36,10 @@
 import java.util.AbstractCollection;
 import java.util.AbstractMap;
 import java.util.AbstractSet;
+import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Iterator;
+import java.util.List;
 import java.util.Map;
 import java.util.NoSuchElementException;
 import java.util.Set;
@@ -53,13 +54,13 @@ final class ByteBufBsonDocument extends BsonDocument {
     private final transient ByteBuf byteBuf;
 
     /**
-     * Create a {@link BsonArray} of ByteBufBsonDocument from a buffer positioned at the start of the first document of an OP_MSG Section
+     * Create a list of ByteBufBsonDocument from a buffer positioned at the start of the first document of an OP_MSG Section
      * of type Document Sequence (Kind 1).
      * <p>
      * The provided buffer will be positioned at the end of the section upon normal completion of the method
      */
-    static BsonArray createBsonArray(final ByteBuf outputByteBuf) {
-        BsonArray documents = new BsonArray();
+    static List<ByteBufBsonDocument> createList(final ByteBuf outputByteBuf) {
+        List<ByteBufBsonDocument> documents = new ArrayList<>();
         while (outputByteBuf.hasRemaining()) {
             ByteBufBsonDocument curDocument = createOne(outputByteBuf);
             documents.add(curDocument);
diff --git a/driver-core/src/main/com/mongodb/internal/connection/CommandMessage.java b/driver-core/src/main/com/mongodb/internal/connection/CommandMessage.java
index f3a6a06a988..12543e92ccb 100644
--- a/driver-core/src/main/com/mongodb/internal/connection/CommandMessage.java
+++ b/driver-core/src/main/com/mongodb/internal/connection/CommandMessage.java
@@ -26,6 +26,7 @@
 import com.mongodb.internal.connection.MessageSequences.EmptyMessageSequences;
 import com.mongodb.internal.session.SessionContext;
 import com.mongodb.lang.Nullable;
+import org.bson.BsonArray;
 import org.bson.BsonBinaryWriter;
 import org.bson.BsonBoolean;
 import org.bson.BsonDocument;
@@ -56,7 +57,7 @@
 import static com.mongodb.internal.connection.BsonWriterHelper.backpatchLength;
 import static com.mongodb.internal.connection.BsonWriterHelper.writeDocumentsOfDualMessageSequences;
 import static com.mongodb.internal.connection.BsonWriterHelper.writePayload;
-import static com.mongodb.internal.connection.ByteBufBsonDocument.createBsonArray;
+import static com.mongodb.internal.connection.ByteBufBsonDocument.createList;
 import static com.mongodb.internal.connection.ByteBufBsonDocument.createOne;
 import static com.mongodb.internal.connection.ReadConcernHelper.getReadConcernDocument;
 import static com.mongodb.internal.operation.ServerVersionHelper.UNKNOWN_WIRE_VERSION;
@@ -167,7 +168,7 @@ BsonDocument getCommandDocument(final ByteBufferBsonOutput bsonOutput) {
 
                         ByteBuf documentsByteBufSlice = byteBuf.duplicate().limit(sectionEnd);
                         try {
-                            commandBsonDocument.append(fieldName, createBsonArray(documentsByteBufSlice));
+                            commandBsonDocument.append(fieldName, new BsonArray(createList(documentsByteBufSlice)));
                         } finally {
                             documentsByteBufSlice.release();
                         }
diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/ByteBufBsonDocumentSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/ByteBufBsonDocumentSpecification.groovy
index f86ae0a16b5..8dc599706a9 100644
--- a/driver-core/src/test/unit/com/mongodb/internal/connection/ByteBufBsonDocumentSpecification.groovy
+++ b/driver-core/src/test/unit/com/mongodb/internal/connection/ByteBufBsonDocumentSpecification.groovy
@@ -310,30 +310,4 @@ class ByteBufBsonDocumentSpecification extends Specification {
         }
     }
 
-    def "createBsonArray should create array of documents from BSON buffer"() {
-        given:
-        def bsonData = [
-                0x13, 0x00, 0x00, 0x00, // Document size (13 bytes)
-                0x10, 'a'.bytes[0], 0x00, 0x01, 0x00, 0x00, 0x00, // Int32 field "a" with value 1
-                0x10, 'b'.bytes[0], 0x00, 0x02, 0x00, 0x00, 0x00, // Int32 field "b" with value 2
-                0x00, // End of document
-
-                0x13, 0x00, 0x00, 0x00, // Document size (13 bytes)
-                0x10, 'c'.bytes[0], 0x00, 0x05, 0x00, 0x00, 0x00, // Int32 field "c" with value 5
-                0x10, 'd'.bytes[0], 0x00, 0x04, 0x00, 0x00, 0x00, // Int32 field "d" with value 4
-                0x00 // End of document
-        ] as byte[]
-        def byteBuf = new ByteBufNIO(ByteBuffer.wrap(bsonData))
-
-        when:
-        def result = ByteBufBsonDocument.createBsonArray(byteBuf)
-
-        then:
-        result.size() == 2
-        result[0].get("a") == new BsonInt32(1)
-        result[0].get("b") == new BsonInt32(2)
-
-        result[1].get("c") == new BsonInt32(5)
-        result[1].get("d") == new BsonInt32(4)
-    }
 }

From 68d1e72346b508f2603848625e03562042593981 Mon Sep 17 00:00:00 2001
From: "slav.babanin" <slav.babanin@mongodb.com>
Date: Wed, 16 Apr 2025 15:37:46 -0700
Subject: [PATCH 4/4] Rename field names to better alight with implementation
 logic.

JAVA-5852
---
 bson/src/main/org/bson/AbstractBsonWriter.java | 16 ++++++++--------
 bson/src/main/org/bson/BsonBinaryWriter.java   | 12 ++++++------
 2 files changed, 14 insertions(+), 14 deletions(-)

diff --git a/bson/src/main/org/bson/AbstractBsonWriter.java b/bson/src/main/org/bson/AbstractBsonWriter.java
index d0ec8ffa4ed..9d571862af0 100644
--- a/bson/src/main/org/bson/AbstractBsonWriter.java
+++ b/bson/src/main/org/bson/AbstractBsonWriter.java
@@ -36,7 +36,7 @@
  */
 public abstract class AbstractBsonWriter implements BsonWriter, Closeable {
     private final BsonWriterSettings settings;
-    private final Deque<FieldNameValidator> fieldNameValidatorQueue = new ArrayDeque<>();
+    private final Deque<FieldNameValidator> fieldNameValidatorStack = new ArrayDeque<>();
     private State state;
     private Context context;
     private int serializationDepth;
@@ -62,7 +62,7 @@ protected AbstractBsonWriter(final BsonWriterSettings settings, final FieldNameV
             throw new IllegalArgumentException("Validator can not be null");
         }
         this.settings = settings;
-        fieldNameValidatorQueue.push(validator);
+        fieldNameValidatorStack.push(validator);
         state = State.INITIAL;
     }
 
@@ -277,8 +277,8 @@ public void writeStartDocument(final String name) {
     public void writeStartDocument() {
         checkPreconditions("writeStartDocument", State.INITIAL, State.VALUE, State.SCOPE_DOCUMENT, State.DONE);
         if (context != null && context.name != null) {
-            FieldNameValidator validator = fieldNameValidatorQueue.peek().getValidatorForField(getName());
-            fieldNameValidatorQueue.push(validator);
+            FieldNameValidator validator = fieldNameValidatorStack.peek().getValidatorForField(getName());
+            fieldNameValidatorStack.push(validator);
             validator.start();
         }
         serializationDepth++;
@@ -301,7 +301,7 @@ public void writeEndDocument() {
         }
 
         if (context.getParentContext() != null && context.getParentContext().name != null) {
-            fieldNameValidatorQueue.pop().end();
+            fieldNameValidatorStack.pop().end();
         }
         serializationDepth--;
 
@@ -325,7 +325,7 @@ public void writeStartArray() {
         checkPreconditions("writeStartArray", State.VALUE);
 
         if (context != null && context.name != null) {
-            fieldNameValidatorQueue.push(fieldNameValidatorQueue.peek().getValidatorForField(getName()));
+            fieldNameValidatorStack.push(fieldNameValidatorStack.peek().getValidatorForField(getName()));
         }
         serializationDepth++;
         if (serializationDepth > settings.getMaxSerializationDepth()) {
@@ -346,7 +346,7 @@ public void writeEndArray() {
         }
 
         if (context.getParentContext() != null && context.getParentContext().name != null) {
-            fieldNameValidatorQueue.pop();
+            fieldNameValidatorStack.pop();
         }
         serializationDepth--;
 
@@ -531,7 +531,7 @@ public void writeName(final String name) {
         if (state != State.NAME) {
             throwInvalidState("WriteName", State.NAME);
         }
-        FieldNameValidator fieldNameValidator = fieldNameValidatorQueue.peek();
+        FieldNameValidator fieldNameValidator = fieldNameValidatorStack.peek();
         if (!fieldNameValidator.validate(name)) {
             throw new IllegalArgumentException(fieldNameValidator.getValidationErrorMessage(name));
         }
diff --git a/bson/src/main/org/bson/BsonBinaryWriter.java b/bson/src/main/org/bson/BsonBinaryWriter.java
index f6e6e436c09..20e73d97d44 100644
--- a/bson/src/main/org/bson/BsonBinaryWriter.java
+++ b/bson/src/main/org/bson/BsonBinaryWriter.java
@@ -38,7 +38,7 @@ public class BsonBinaryWriter extends AbstractBsonWriter {
     private final BsonBinaryWriterSettings binaryWriterSettings;
 
     private final BsonOutput bsonOutput;
-    private final Deque<Integer> maxDocumentSizeQueue = new ArrayDeque<>();
+    private final Deque<Integer> maxDocumentSizeStack = new ArrayDeque<>();
     private static final int ARRAY_INDEXES_CACHE_SIZE = 1000;
     private static final byte[] ARRAY_INDEXES_BUFFER;
     private static final int[] ARRAY_INDEXES_OFFSETS;
@@ -114,7 +114,7 @@ public BsonBinaryWriter(final BsonWriterSettings settings, final BsonBinaryWrite
         super(settings, validator);
         this.binaryWriterSettings = binaryWriterSettings;
         this.bsonOutput = bsonOutput;
-        maxDocumentSizeQueue.push(binaryWriterSettings.getMaxDocumentSize());
+        maxDocumentSizeStack.push(binaryWriterSettings.getMaxDocumentSize());
     }
 
     @Override
@@ -395,14 +395,14 @@ private void pipeDocument(final BsonReader reader, final List<BsonElement> extra
      * @param maxDocumentSize the maximum document size.
      */
     public void pushMaxDocumentSize(final int maxDocumentSize) {
-        maxDocumentSizeQueue.push(maxDocumentSize);
+        maxDocumentSizeStack.push(maxDocumentSize);
     }
 
     /**
      * Reset the maximum document size to its previous value.
      */
     public void popMaxDocumentSize() {
-        maxDocumentSizeQueue.pop();
+        maxDocumentSizeStack.pop();
     }
 
     /**
@@ -448,9 +448,9 @@ private void backpatchSize() {
     }
 
     private void validateSize(final int size) {
-        if (size > maxDocumentSizeQueue.peek()) {
+        if (size > maxDocumentSizeStack.peek()) {
             throw new BsonMaximumSizeExceededException(format("Document size of %d is larger than maximum of %d.", size,
-                    maxDocumentSizeQueue.peek()));
+                    maxDocumentSizeStack.peek()));
         }
     }