You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by ku...@apache.org on 2019/03/11 04:23:42 UTC

[flink] branch master updated: [FLINK-11857][table-runtime-blink] Introduce BinaryExternalSorter and BufferedKVExternalSorter to batch table runtime (#7945)

This is an automated email from the ASF dual-hosted git repository.

kurt pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink.git


The following commit(s) were added to refs/heads/master by this push:
     new 2819e6c  [FLINK-11857][table-runtime-blink] Introduce BinaryExternalSorter and BufferedKVExternalSorter to batch table runtime (#7945)
2819e6c is described below

commit 2819e6c230f3e57097f15c250fb01c3155168396
Author: Jingsong Lee <lz...@aliyun.com>
AuthorDate: Mon Mar 11 12:23:27 2019 +0800

    [FLINK-11857][table-runtime-blink] Introduce BinaryExternalSorter and BufferedKVExternalSorter to batch table runtime (#7945)
---
 .../common/typeutils/base/BooleanComparator.java   |    8 +-
 .../api/common/typeutils/base/ByteComparator.java  |   19 +-
 .../api/common/typeutils/base/CharComparator.java  |   21 +-
 .../api/common/typeutils/base/IntComparator.java   |   21 +-
 .../api/common/typeutils/base/LongComparator.java  |   21 +-
 .../common/typeutils/base/NormalizedKeyUtil.java   |  153 +++
 .../api/common/typeutils/base/ShortComparator.java |   24 +-
 .../io/disk/ChannelReaderInputViewIterator.java    |    5 +-
 .../HeaderlessChannelReaderInputView.java          |    2 +-
 .../runtime/memory/AbstractPagedInputView.java     |    9 +-
 .../runtime/memory/AbstractPagedOutputView.java    |    9 +-
 .../apache/flink/table/api/TableConfigOptions.java |   65 ++
 .../flink/table/dataformat/BinaryString.java       |  145 ++-
 .../compression/BlockCompressionFactory.java       |   57 +
 .../runtime/io/CompressedBlockChannelReader.java   |    2 +-
 .../runtime/sort/AbstractBinaryExternalMerger.java |  224 ++++
 .../table/runtime/sort/BinaryExternalMerger.java   |   87 ++
 .../table/runtime/sort/BinaryExternalSorter.java   | 1168 ++++++++++++++++++++
 .../runtime/sort/BinaryInMemorySortBuffer.java     |  222 ++++
 .../table/runtime/sort/BinaryIndexedSortable.java  |  250 +++++
 .../table/runtime/sort/BinaryKVExternalMerger.java |   94 ++
 .../runtime/sort/BinaryKVInMemorySortBuffer.java   |   98 ++
 .../table/runtime/sort/BinaryMergeIterator.java    |   98 ++
 .../runtime/sort/BufferedKVExternalSorter.java     |  184 +++
 .../sort/ChannelReaderKVInputViewIterator.java     |   70 ++
 .../table/runtime/sort/ListMemorySegmentPool.java  |   62 ++
 .../table/runtime/sort/NormalizedKeyComputer.java  |   69 ++
 .../flink/table/runtime/sort/RecordComparator.java |   46 +
 .../apache/flink/table/runtime/sort/SortUtil.java  |  120 ++
 .../table/runtime/sort/SpillChannelManager.java    |  101 ++
 .../MemorySegmentPool.java}                        |   27 +-
 .../table/typeutils/AbstractRowSerializer.java     |   95 ++
 .../flink/table/typeutils/BaseRowSerializer.java   |   37 +-
 .../flink/table/typeutils/BinaryRowSerializer.java |  150 ++-
 .../flink/table/dataformat/BinaryRowTest.java      |   77 ++
 .../flink/table/dataformat/BinaryStringTest.java   |  259 +++++
 .../runtime/sort/BinaryExternalSorterTest.java     |  420 +++++++
 .../runtime/sort/BinaryMergeIteratorTest.java      |  176 +++
 .../runtime/sort/BufferedKVExternalSorterTest.java |  169 +++
 .../runtime/sort/IntNormalizedKeyComputer.java     |   89 ++
 .../table/runtime/sort/IntRecordComparator.java}   |   25 +-
 .../flink/table/runtime/sort/SortUtilTest.java     |  132 +++
 .../table/runtime/sort/TestMemorySegmentPool.java} |   37 +-
 43 files changed, 5012 insertions(+), 135 deletions(-)

diff --git a/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/BooleanComparator.java b/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/BooleanComparator.java
index 290b8d0..f0e5026 100644
--- a/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/BooleanComparator.java
+++ b/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/BooleanComparator.java
@@ -60,13 +60,7 @@ public final class BooleanComparator extends BasicTypeComparator<Boolean> {
 
 	@Override
 	public void putNormalizedKey(Boolean value, MemorySegment target, int offset, int numBytes) {
-		if (numBytes > 0) {
-			target.put(offset, (byte) (value.booleanValue() ? 1 : 0));
-			
-			for (offset = offset + 1; numBytes > 1; numBytes--) {
-				target.put(offset++, (byte) 0);
-			}
-		}
+		NormalizedKeyUtil.putBooleanNormalizedKey(value, target, offset, numBytes);
 	}
 
 	@Override
diff --git a/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/ByteComparator.java b/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/ByteComparator.java
index d98b1c7..46f0468 100644
--- a/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/ByteComparator.java
+++ b/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/ByteComparator.java
@@ -60,24 +60,7 @@ public final class ByteComparator extends BasicTypeComparator<Byte> {
 
 	@Override
 	public void putNormalizedKey(Byte value, MemorySegment target, int offset, int numBytes) {
-		if (numBytes == 1) {
-			// default case, full normalized key. need to explicitly convert to int to
-			// avoid false results due to implicit type conversion to int when subtracting
-			// the min byte value
-			int highByte = value & 0xff;
-			highByte -= Byte.MIN_VALUE;
-			target.put(offset, (byte) highByte);
-		}
-		else if (numBytes <= 0) {
-		}
-		else {
-			int highByte = value & 0xff;
-			highByte -= Byte.MIN_VALUE;
-			target.put(offset, (byte) highByte);
-			for (int i = 1; i < numBytes; i++) {
-				target.put(offset + i, (byte) 0);
-			}
-		}
+		NormalizedKeyUtil.putByteNormalizedKey(value, target, offset, numBytes);
 	}
 
 	@Override
diff --git a/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/CharComparator.java b/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/CharComparator.java
index 3e36b4c..9bc1d5d 100644
--- a/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/CharComparator.java
+++ b/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/CharComparator.java
@@ -59,26 +59,7 @@ public final class CharComparator extends BasicTypeComparator<Character> {
 
 	@Override
 	public void putNormalizedKey(Character value, MemorySegment target, int offset, int numBytes) {
-		// note that the char is an unsigned data type in java and consequently needs
-		// no code that transforms the signed representation to an offset representation
-		// that is equivalent to unsigned, when compared byte by byte
-		if (numBytes == 2) {
-			// default case, full normalized key
-			target.put(offset,     (byte) ((value >>> 8) & 0xff));
-			target.put(offset + 1, (byte) ((value      ) & 0xff));
-		}
-		else if (numBytes <= 0) {
-		}
-		else if (numBytes == 1) {
-			target.put(offset,     (byte) ((value >>> 8) & 0xff));
-		}
-		else {
-			target.put(offset,     (byte) ((value >>> 8) & 0xff));
-			target.put(offset + 1, (byte) ((value      ) & 0xff));
-			for (int i = 2; i < numBytes; i++) {
-				target.put(offset + i, (byte) 0);
-			}
-		}
+		NormalizedKeyUtil.putCharNormalizedKey(value, target, offset, numBytes);
 	}
 
 	@Override
diff --git a/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/IntComparator.java b/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/IntComparator.java
index b86e405..bbd5a80 100644
--- a/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/IntComparator.java
+++ b/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/IntComparator.java
@@ -60,26 +60,7 @@ public final class IntComparator extends BasicTypeComparator<Integer> {
 
 	@Override
 	public void putNormalizedKey(Integer iValue, MemorySegment target, int offset, int numBytes) {
-		int value = iValue.intValue() - Integer.MIN_VALUE;
-		
-		// see IntValue for an explanation of the logic
-		if (numBytes == 4) {
-			// default case, full normalized key
-			target.putIntBigEndian(offset, value);
-		}
-		else if (numBytes <= 0) {
-		}
-		else if (numBytes < 4) {
-			for (int i = 0; numBytes > 0; numBytes--, i++) {
-				target.put(offset + i, (byte) (value >>> ((3-i)<<3)));
-			}
-		}
-		else {
-			target.putLongBigEndian(offset, value);
-			for (int i = 4; i < numBytes; i++) {
-				target.put(offset + i, (byte) 0);
-			}
-		}
+		NormalizedKeyUtil.putIntNormalizedKey(iValue, target, offset, numBytes);
 	}
 
 	@Override
diff --git a/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/LongComparator.java b/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/LongComparator.java
index 6cee97f..b65574f 100644
--- a/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/LongComparator.java
+++ b/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/LongComparator.java
@@ -60,26 +60,7 @@ public final class LongComparator extends BasicTypeComparator<Long> {
 
 	@Override
 	public void putNormalizedKey(Long lValue, MemorySegment target, int offset, int numBytes) {
-		long value = lValue.longValue() - Long.MIN_VALUE;
-		
-		// see IntValue for an explanation of the logic
-		if (numBytes == 8) {
-			// default case, full normalized key
-			target.putLongBigEndian(offset, value);
-		}
-		else if (numBytes <= 0) {
-		}
-		else if (numBytes < 8) {
-			for (int i = 0; numBytes > 0; numBytes--, i++) {
-				target.put(offset + i, (byte) (value >>> ((7-i)<<3)));
-			}
-		}
-		else {
-			target.putLongBigEndian(offset, value);
-			for (int i = 8; i < numBytes; i++) {
-				target.put(offset + i, (byte) 0);
-			}
-		}
+		NormalizedKeyUtil.putLongNormalizedKey(lValue, target, offset, numBytes);
 	}
 
 	@Override
diff --git a/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/NormalizedKeyUtil.java b/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/NormalizedKeyUtil.java
new file mode 100644
index 0000000..7adbf75
--- /dev/null
+++ b/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/NormalizedKeyUtil.java
@@ -0,0 +1,153 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.api.common.typeutils.base;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.api.common.typeutils.TypeComparator;
+import org.apache.flink.core.memory.MemorySegment;
+
+/**
+ * Utilities related to {@link TypeComparator}.
+ */
+@Internal
+public class NormalizedKeyUtil {
+
+	public static void putByteNormalizedKey(byte value, MemorySegment target, int offset, int numBytes) {
+		if (numBytes == 1) {
+			// default case, full normalized key. need to explicitly convert to int to
+			// avoid false results due to implicit type conversion to int when subtracting
+			// the min byte value
+			int highByte = value & 0xff;
+			highByte -= Byte.MIN_VALUE;
+			target.put(offset, (byte) highByte);
+		}
+		else if (numBytes <= 0) {
+		}
+		else {
+			int highByte = value & 0xff;
+			highByte -= Byte.MIN_VALUE;
+			target.put(offset, (byte) highByte);
+			for (int i = 1; i < numBytes; i++) {
+				target.put(offset + i, (byte) 0);
+			}
+		}
+	}
+
+	public static void putCharNormalizedKey(char value, MemorySegment target, int offset, int numBytes) {
+		// note that the char is an unsigned data type in java and consequently needs
+		// no code that transforms the signed representation to an offset representation
+		// that is equivalent to unsigned, when compared byte by byte
+		if (numBytes == 2) {
+			// default case, full normalized key
+			target.put(offset,     (byte) ((value >>> 8) & 0xff));
+			target.put(offset + 1, (byte) ((value) & 0xff));
+		}
+		else if (numBytes <= 0) {
+		}
+		else if (numBytes == 1) {
+			target.put(offset,     (byte) ((value >>> 8) & 0xff));
+		}
+		else {
+			target.put(offset,     (byte) ((value >>> 8) & 0xff));
+			target.put(offset + 1, (byte) ((value) & 0xff));
+			for (int i = 2; i < numBytes; i++) {
+				target.put(offset + i, (byte) 0);
+			}
+		}
+	}
+
+	public static void putBooleanNormalizedKey(boolean value, MemorySegment target, int offset, int numBytes) {
+		if (numBytes > 0) {
+			target.put(offset, (byte) (value ? 1 : 0));
+
+			for (offset = offset + 1; numBytes > 1; numBytes--) {
+				target.put(offset++, (byte) 0);
+			}
+		}
+	}
+
+	public static void putShortNormalizedKey(short value, MemorySegment target, int offset, int numBytes) {
+		if (numBytes == 2) {
+			// default case, full normalized key
+			int highByte = ((value >>> 8) & 0xff);
+			highByte -= Byte.MIN_VALUE;
+			target.put(offset, (byte) highByte);
+			target.put(offset + 1, (byte) ((value) & 0xff));
+		}
+		else if (numBytes <= 0) {
+		}
+		else if (numBytes == 1) {
+			int highByte = ((value >>> 8) & 0xff);
+			highByte -= Byte.MIN_VALUE;
+			target.put(offset, (byte) highByte);
+		}
+		else {
+			int highByte = ((value >>> 8) & 0xff);
+			highByte -= Byte.MIN_VALUE;
+			target.put(offset, (byte) highByte);
+			target.put(offset + 1, (byte) ((value) & 0xff));
+			for (int i = 2; i < numBytes; i++) {
+				target.put(offset + i, (byte) 0);
+			}
+		}
+	}
+
+	public static void putIntNormalizedKey(int iValue, MemorySegment target, int offset, int numBytes) {
+		putUnsignedIntegerNormalizedKey(iValue - Integer.MIN_VALUE, target, offset, numBytes);
+	}
+
+	public static void putUnsignedIntegerNormalizedKey(int value, MemorySegment target, int offset, int numBytes) {
+		if (numBytes == 4) {
+			// default case, full normalized key
+			target.putIntBigEndian(offset, value);
+		} else if (numBytes > 0) {
+			if (numBytes < 4) {
+				for (int i = 0; numBytes > 0; numBytes--, i++) {
+					target.put(offset + i, (byte) (value >>> ((3 - i) << 3)));
+				}
+			} else {
+				target.putIntBigEndian(offset, value);
+				for (int i = 4; i < numBytes; i++) {
+					target.put(offset + i, (byte) 0);
+				}
+			}
+		}
+	}
+
+	public static void putLongNormalizedKey(long lValue, MemorySegment target, int offset, int numBytes) {
+		putUnsignedLongNormalizedKey(lValue - Long.MIN_VALUE, target, offset, numBytes);
+	}
+
+	public static void putUnsignedLongNormalizedKey(long value, MemorySegment target, int offset, int numBytes) {
+		if (numBytes == 8) {
+			// default case, full normalized key
+			target.putLongBigEndian(offset, value);
+		} else if (numBytes > 0) {
+			if (numBytes < 8) {
+				for (int i = 0; numBytes > 0; numBytes--, i++) {
+					target.put(offset + i, (byte) (value >>> ((7 - i) << 3)));
+				}
+			} else {
+				target.putLongBigEndian(offset, value);
+				for (int i = 8; i < numBytes; i++) {
+					target.put(offset + i, (byte) 0);
+				}
+			}
+		}
+	}
+}
diff --git a/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/ShortComparator.java b/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/ShortComparator.java
index e88d77a..6c82886 100644
--- a/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/ShortComparator.java
+++ b/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/ShortComparator.java
@@ -59,29 +59,7 @@ public final class ShortComparator extends BasicTypeComparator<Short> {
 
 	@Override
 	public void putNormalizedKey(Short value, MemorySegment target, int offset, int numBytes) {
-		if (numBytes == 2) {
-			// default case, full normalized key
-			int highByte = ((value >>> 8) & 0xff);
-			highByte -= Byte.MIN_VALUE;
-			target.put(offset, (byte) highByte);
-			target.put(offset + 1, (byte) ((value) & 0xff));
-		}
-		else if (numBytes <= 0) {
-		}
-		else if (numBytes == 1) {
-			int highByte = ((value >>> 8) & 0xff);
-			highByte -= Byte.MIN_VALUE;
-			target.put(offset, (byte) highByte);
-		}
-		else {
-			int highByte = ((value >>> 8) & 0xff);
-			highByte -= Byte.MIN_VALUE;
-			target.put(offset, (byte) highByte);
-			target.put(offset + 1, (byte) ((value) & 0xff));
-			for (int i = 2; i < numBytes; i++) {
-				target.put(offset + i, (byte) 0);
-			}
-		}
+		NormalizedKeyUtil.putShortNormalizedKey(value, target, offset, numBytes);
 	}
 
 	@Override
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/disk/ChannelReaderInputViewIterator.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/disk/ChannelReaderInputViewIterator.java
index 87a3baa..034a764 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/io/disk/ChannelReaderInputViewIterator.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/disk/ChannelReaderInputViewIterator.java
@@ -26,6 +26,7 @@ import java.util.concurrent.LinkedBlockingQueue;
 
 import org.apache.flink.api.common.typeutils.TypeSerializer;
 import org.apache.flink.core.memory.MemorySegment;
+import org.apache.flink.runtime.io.disk.iomanager.AbstractChannelReaderInputView;
 import org.apache.flink.runtime.io.disk.iomanager.BlockChannelReader;
 import org.apache.flink.runtime.io.disk.iomanager.FileIOChannel;
 import org.apache.flink.runtime.io.disk.iomanager.ChannelReaderInputView;
@@ -39,7 +40,7 @@ import org.apache.flink.util.MutableObjectIterator;
  */
 public class ChannelReaderInputViewIterator<E> implements MutableObjectIterator<E>
 {
-	private final ChannelReaderInputView inView;
+	private final AbstractChannelReaderInputView inView;
 	
 	private final TypeSerializer<E> accessors;
 	
@@ -70,7 +71,7 @@ public class ChannelReaderInputViewIterator<E> implements MutableObjectIterator<
 		this.inView = new ChannelReaderInputView(reader, segments, numBlocks, false);
 	}
 	
-	public ChannelReaderInputViewIterator(ChannelReaderInputView inView, List<MemorySegment> freeMemTarget, TypeSerializer<E> accessors)
+	public ChannelReaderInputViewIterator(AbstractChannelReaderInputView inView, List<MemorySegment> freeMemTarget, TypeSerializer<E> accessors)
 	{
 		this.inView = inView;
 		this.freeMemTarget = freeMemTarget;
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/disk/iomanager/HeaderlessChannelReaderInputView.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/disk/iomanager/HeaderlessChannelReaderInputView.java
index 9d45205..25439ab 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/io/disk/iomanager/HeaderlessChannelReaderInputView.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/disk/iomanager/HeaderlessChannelReaderInputView.java
@@ -119,7 +119,7 @@ public class HeaderlessChannelReaderInputView extends ChannelReaderInputView {
 	}
 
 	@Override
-	protected void advance() throws IOException {
+	public void advance() throws IOException {
 		doAdvance();
 		if (isFirstBlock && offset > 0) {
 			seekInput(getCurrentSegment(), (int) offset, getCurrentSegmentLimit());
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/memory/AbstractPagedInputView.java b/flink-runtime/src/main/java/org/apache/flink/runtime/memory/AbstractPagedInputView.java
index d73aeaa..3efb836 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/memory/AbstractPagedInputView.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/memory/AbstractPagedInputView.java
@@ -152,7 +152,7 @@ public abstract class AbstractPagedInputView implements DataInputView {
 	 * @see #nextSegment(MemorySegment)
 	 * @see #getLimitForSegment(MemorySegment)
 	 */
-	protected void advance() throws IOException {
+	public void advance() throws IOException {
 		doAdvance();
 	}
 
@@ -165,6 +165,13 @@ public abstract class AbstractPagedInputView implements DataInputView {
 	}
 
 	/**
+	 * @return header length.
+	 */
+	public int getHeaderLength() {
+		return headerLength;
+	}
+
+	/**
 	 * Sets the internal state of the view such that the next bytes will be read from the given memory segment,
 	 * starting at the given position. The memory segment will provide bytes up to the given limit position.
 	 *
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/memory/AbstractPagedOutputView.java b/flink-runtime/src/main/java/org/apache/flink/runtime/memory/AbstractPagedOutputView.java
index ddb909f..fbb6d5e 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/memory/AbstractPagedOutputView.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/memory/AbstractPagedOutputView.java
@@ -133,12 +133,19 @@ public abstract class AbstractPagedOutputView implements DataOutputView {
 	 * @throws IOException Thrown, if the current segment could not be processed or a new segment could not
 	 *                     be obtained.
 	 */
-	protected void advance() throws IOException {
+	public void advance() throws IOException {
 		this.currentSegment = nextSegment(this.currentSegment, this.positionInSegment);
 		this.positionInSegment = this.headerLength;
 	}
 
 	/**
+	 * @return header length.
+	 */
+	public int getHeaderLength() {
+		return headerLength;
+	}
+
+	/**
 	 * Sets the internal state to the given memory segment and the given position within the segment.
 	 *
 	 * @param seg The memory segment to write the next bytes to.
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/api/TableConfigOptions.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/api/TableConfigOptions.java
new file mode 100644
index 0000000..b4afcc1
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/api/TableConfigOptions.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.api;
+
+import org.apache.flink.configuration.ConfigOption;
+
+import static org.apache.flink.configuration.ConfigOptions.key;
+
+/**
+ * This class holds configuration constants used by Flink's table module.
+ */
+public class TableConfigOptions {
+
+	// ------------------------------------------------------------------------
+	//  Sort Options
+	// ------------------------------------------------------------------------
+
+	public static final ConfigOption<Integer> SQL_EXEC_SORT_FILE_HANDLES_MAX_NUM =
+			key("sql.exec.sort.file-handles.max.num")
+					.defaultValue(128)
+					.withDescription("Sort merge's maximum number of roads, too many roads, may cause too many files to be" +
+							" read at the same time, resulting in excessive use of memory.");
+
+	public static final ConfigOption<Boolean> SQL_EXEC_SORT_ASYNC_MERGE_ENABLED =
+			key("sql.exec.sort.async-merge.enabled")
+					.defaultValue(true)
+					.withDescription("Whether to asynchronously merge sort spill files.");
+
+	// ------------------------------------------------------------------------
+	//  Spill Options
+	// ------------------------------------------------------------------------
+
+	public static final ConfigOption<Boolean> SQL_EXEC_SPILL_COMPRESSION_ENABLED =
+			key("sql.exec.spill.compression.enabled")
+					.defaultValue(true)
+					.withDescription("Whether to compress spilled data. (Now include sort and hash agg and hash join)");
+
+	public static final ConfigOption<String> SQL_EXEC_SPILL_COMPRESSION_CODEC =
+			key("sql.exec.spill.compression.codec")
+					.defaultValue("lz4")
+					.withDescription("Use that compression codec to compress spilled file. Now we support lz4, gzip, bzip2.");
+
+	public static final ConfigOption<Integer> SQL_EXEC_SPILL_COMPRESSION_BLOCK_SIZE =
+			key("sql.exec.spill.compression.block-size")
+					.defaultValue(64 * 1024)
+					.withDescription("The buffer is to compress. The larger the buffer," +
+							" the better the compression ratio, but the more memory consumption.");
+
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/dataformat/BinaryString.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/dataformat/BinaryString.java
index f6ac5c2..0db18b4 100644
--- a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/dataformat/BinaryString.java
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/dataformat/BinaryString.java
@@ -21,6 +21,10 @@ import org.apache.flink.core.memory.MemorySegment;
 import org.apache.flink.core.memory.MemorySegmentFactory;
 import org.apache.flink.table.util.SegmentsUtil;
 
+import java.util.Arrays;
+
+import static org.apache.flink.util.Preconditions.checkArgument;
+
 /**
  * A utf8 string which is backed by {@link MemorySegment} instead of String. Its data may span
  * multiple {@link MemorySegment}s.
@@ -30,7 +34,7 @@ import org.apache.flink.table.util.SegmentsUtil;
  *
  * <p>{@code BinaryString} are influenced by Apache Spark UTF8String.
  */
-public class BinaryString extends LazyBinaryFormat<String> {
+public class BinaryString extends LazyBinaryFormat<String> implements Comparable<BinaryString> {
 
 	private static final long HIGHEST_FIRST_BIT = Long.MIN_VALUE;
 	private static final long HIGHEST_SECOND_TO_EIGHTH_BIT = 0x7FL << 56;
@@ -49,6 +53,14 @@ public class BinaryString extends LazyBinaryFormat<String> {
 		super(segments, offset, sizeInBytes, javaObject);
 	}
 
+	/**
+	 * Creates an BinaryString from given address (base and offset) and length.
+	 */
+	public static BinaryString fromAddress(
+			MemorySegment[] segments, int offset, int numBytes) {
+		return new BinaryString(segments, offset, numBytes);
+	}
+
 	public static BinaryString fromString(String str) {
 		if (str == null) {
 			return null;
@@ -62,6 +74,26 @@ public class BinaryString extends LazyBinaryFormat<String> {
 				new MemorySegment[] {MemorySegmentFactory.wrap(bytes)}, 0, bytes.length);
 	}
 
+	/**
+	 * Creates an BinaryString that contains `length` spaces.
+	 */
+	public static BinaryString blankString(int length) {
+		byte[] spaces = new byte[length];
+		Arrays.fill(spaces, (byte) ' ');
+		return fromBytes(spaces);
+	}
+
+	public byte getByte(int i) {
+		ensureMaterialized();
+		int globalOffset = offset + i;
+		int size = segments[0].size();
+		if (globalOffset < size) {
+			return segments[0].get(globalOffset);
+		} else {
+			return segments[globalOffset / size].get(globalOffset % size);
+		}
+	}
+
 	@Override
 	public boolean equals(Object o) {
 		if (o != null && o instanceof BinaryString) {
@@ -104,6 +136,117 @@ public class BinaryString extends LazyBinaryFormat<String> {
 	}
 
 	/**
+	 * UTF-8 supports bytes comparison.
+	 */
+	@Override
+	public int compareTo(BinaryString other) {
+
+		if (javaObject != null && other.javaObject != null) {
+			return javaObject.compareTo(other.javaObject);
+		}
+
+		ensureMaterialized();
+		other.ensureMaterialized();
+		if (segments.length == 1 && other.segments.length == 1) {
+
+			int len = Math.min(sizeInBytes, other.sizeInBytes);
+			MemorySegment seg1 = segments[0];
+			MemorySegment seg2 = other.segments[0];
+
+			for (int i = 0; i < len; i++) {
+				int res = (seg1.get(offset + i) & 0xFF) - (seg2.get(other.offset + i) & 0xFF);
+				if (res != 0) {
+					return res;
+				}
+			}
+			return sizeInBytes - other.sizeInBytes;
+		}
+
+		// if there are multi segments.
+		return compareMultiSegments(other);
+	}
+
+	/**
+	 * Find the boundaries of segments, and then compare MemorySegment.
+	 */
+	private int compareMultiSegments(BinaryString other) {
+
+		if (sizeInBytes == 0 || other.sizeInBytes == 0) {
+			return sizeInBytes - other.sizeInBytes;
+		}
+
+		int len = Math.min(sizeInBytes, other.sizeInBytes);
+
+		MemorySegment seg1 = segments[0];
+		MemorySegment seg2 = other.segments[0];
+
+		int segmentSize = segments[0].size();
+		int otherSegmentSize = other.segments[0].size();
+
+		int sizeOfFirst1 = segmentSize - offset;
+		int sizeOfFirst2 = otherSegmentSize - other.offset;
+
+		int varSegIndex1 = 1;
+		int varSegIndex2 = 1;
+
+		// find the first segment of this string.
+		while (sizeOfFirst1 <= 0) {
+			sizeOfFirst1 += segmentSize;
+			seg1 = segments[varSegIndex1++];
+		}
+
+		while (sizeOfFirst2 <= 0) {
+			sizeOfFirst2 += otherSegmentSize;
+			seg2 = other.segments[varSegIndex2++];
+		}
+
+		int offset1 = segmentSize - sizeOfFirst1;
+		int offset2 = otherSegmentSize - sizeOfFirst2;
+
+		int needCompare = Math.min(Math.min(sizeOfFirst1, sizeOfFirst2), len);
+
+		while (needCompare > 0) {
+			// compare in one segment.
+			for (int i = 0; i < needCompare; i++) {
+				int res = (seg1.get(offset1 + i) & 0xFF) - (seg2.get(offset2 + i) & 0xFF);
+				if (res != 0) {
+					return res;
+				}
+			}
+			if (needCompare == len) {
+				break;
+			}
+			len -= needCompare;
+			// next segment
+			if (sizeOfFirst1 < sizeOfFirst2) { //I am smaller
+				seg1 = segments[varSegIndex1++];
+				offset1 = 0;
+				offset2 += needCompare;
+				sizeOfFirst1 = segmentSize;
+				sizeOfFirst2 -= needCompare;
+			} else if (sizeOfFirst1 > sizeOfFirst2) { //other is smaller
+				seg2 = other.segments[varSegIndex2++];
+				offset2 = 0;
+				offset1 += needCompare;
+				sizeOfFirst2 = otherSegmentSize;
+				sizeOfFirst1 -= needCompare;
+			} else { // same, should go ahead both.
+				seg1 = segments[varSegIndex1++];
+				seg2 = other.segments[varSegIndex2++];
+				offset1 = 0;
+				offset2 = 0;
+				sizeOfFirst1 = segmentSize;
+				sizeOfFirst2 = otherSegmentSize;
+			}
+			needCompare = Math.min(Math.min(sizeOfFirst1, sizeOfFirst2), len);
+		}
+
+		checkArgument(needCompare == len);
+
+		return sizeInBytes - other.sizeInBytes;
+	}
+
+	/**
 	 * Get binary string, if len less than 8, will be include in variablePartOffsetAndLen.
 	 *
 	 * <p>If len is less than 8, its binary format is:
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/compression/BlockCompressionFactory.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/compression/BlockCompressionFactory.java
index a3c1261..e2384c4 100644
--- a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/compression/BlockCompressionFactory.java
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/compression/BlockCompressionFactory.java
@@ -18,6 +18,10 @@
 
 package org.apache.flink.table.runtime.compression;
 
+import org.apache.flink.configuration.IllegalConfigurationException;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
 /**
  * Each compression codec has a implementation of {@link BlockCompressionFactory}
  * to create compressors and decompressors.
@@ -27,4 +31,57 @@ public interface BlockCompressionFactory {
 	BlockCompressor getCompressor();
 
 	BlockDecompressor getDecompressor();
+
+	/**
+	 * Name of {@link BlockCompressionFactory}.
+	 */
+	enum CompressionFactoryName {
+		LZ4
+	}
+
+	/**
+	 * Creates {@link BlockCompressionFactory} according to the configuration.
+	 * @param compressionFactoryName supported compression codecs or user-defined class name inherited from
+	 *                               {@link BlockCompressionFactory}.
+	 */
+	static BlockCompressionFactory createBlockCompressionFactory(String compressionFactoryName) {
+
+		checkNotNull(compressionFactoryName);
+
+		CompressionFactoryName compressionName;
+		try {
+			compressionName = CompressionFactoryName.valueOf(compressionFactoryName.toUpperCase());
+		} catch (IllegalArgumentException e) {
+			compressionName = null;
+		}
+
+		BlockCompressionFactory blockCompressionFactory = null;
+		if (compressionName != null) {
+			switch (compressionName) {
+				case LZ4:
+					blockCompressionFactory = new Lz4BlockCompressionFactory();
+					break;
+				default:
+					throw new IllegalStateException("Unknown CompressionMethod " + compressionName);
+			}
+		} else {
+			Object factoryObj;
+			try {
+				factoryObj = Class.forName(compressionFactoryName).newInstance();
+			} catch (ClassNotFoundException e) {
+				throw new IllegalConfigurationException("Cannot load class " + compressionFactoryName, e);
+			} catch (Exception e) {
+				throw new IllegalConfigurationException("Cannot create object for class " + compressionFactoryName, e);
+			}
+			if (factoryObj instanceof BlockCompressionFactory) {
+				blockCompressionFactory = (BlockCompressionFactory) factoryObj;
+			} else {
+				throw new IllegalArgumentException("CompressionFactoryName should inherit from" +
+						" interface BlockCompressionFactory, or use the default compression codec.");
+			}
+		}
+
+		checkNotNull(blockCompressionFactory);
+		return blockCompressionFactory;
+	}
 }
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/io/CompressedBlockChannelReader.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/io/CompressedBlockChannelReader.java
index 6be2c2e..d9d1298 100644
--- a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/io/CompressedBlockChannelReader.java
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/io/CompressedBlockChannelReader.java
@@ -120,7 +120,7 @@ public class CompressedBlockChannelReader
 	private int decompressBuffer(ByteBuffer toRead) throws IOException {
 		try {
 			Buffer buffer;
-			while ((buffer = retBuffers.poll(11000, TimeUnit.MILLISECONDS)) == null) {
+			while ((buffer = retBuffers.poll(1000, TimeUnit.MILLISECONDS)) == null) {
 				if (cause.get() != null) {
 					throw cause.get();
 				}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/AbstractBinaryExternalMerger.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/AbstractBinaryExternalMerger.java
new file mode 100644
index 0000000..d559edd
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/AbstractBinaryExternalMerger.java
@@ -0,0 +1,224 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.runtime.io.disk.iomanager.AbstractChannelReaderInputView;
+import org.apache.flink.runtime.io.disk.iomanager.AbstractChannelWriterOutputView;
+import org.apache.flink.runtime.io.disk.iomanager.FileIOChannel;
+import org.apache.flink.runtime.io.disk.iomanager.IOManager;
+import org.apache.flink.runtime.memory.AbstractPagedOutputView;
+import org.apache.flink.table.runtime.compression.BlockCompressionFactory;
+import org.apache.flink.table.runtime.io.ChannelWithMeta;
+import org.apache.flink.table.runtime.util.FileChannelUtil;
+import org.apache.flink.util.MutableObjectIterator;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+
+/**
+ * Spilled files Merger of {@link BinaryExternalSorter}.
+ * It merges {@link #maxFanIn} spilled files at most once.
+ *
+ * @param <Entry> Type of Entry to Merge sort.
+ */
+public abstract class AbstractBinaryExternalMerger<Entry> implements Closeable {
+
+	private static final Logger LOG = LoggerFactory.getLogger(AbstractBinaryExternalMerger.class);
+
+	private volatile boolean closed;
+
+	private final int maxFanIn;
+	private final SpillChannelManager channelManager;
+	private final boolean compressionEnable;
+	private final BlockCompressionFactory compressionCodecFactory;
+	private final int compressionBlockSize;
+
+	protected final int pageSize;
+	protected final IOManager ioManager;
+
+	public AbstractBinaryExternalMerger(
+			IOManager ioManager,
+			int pageSize,
+			int maxFanIn,
+			SpillChannelManager channelManager,
+			boolean compressionEnable,
+			BlockCompressionFactory compressionCodecFactory,
+			int compressionBlockSize) {
+		this.ioManager = ioManager;
+		this.pageSize = pageSize;
+		this.maxFanIn = maxFanIn;
+		this.channelManager = channelManager;
+		this.compressionEnable = compressionEnable;
+		this.compressionCodecFactory = compressionCodecFactory;
+		this.compressionBlockSize = compressionBlockSize;
+	}
+
+	@Override
+	public void close() {
+		this.closed = true;
+	}
+
+	/**
+	 * Returns an iterator that iterates over the merged result from all given channels.
+	 *
+	 * @param channelIDs    The channels that are to be merged and returned.
+	 * @return An iterator over the merged records of the input channels.
+	 * @throws IOException Thrown, if the readers encounter an I/O problem.
+	 */
+	public BinaryMergeIterator<Entry> getMergingIterator(
+			List<ChannelWithMeta> channelIDs,
+			List<FileIOChannel> openChannels)
+			throws IOException {
+		// create one iterator per channel id
+		if (LOG.isDebugEnabled()) {
+			LOG.debug("Performing merge of " + channelIDs.size() + " sorted streams.");
+		}
+
+		final List<MutableObjectIterator<Entry>> iterators = new ArrayList<>(channelIDs.size() + 1);
+
+		for (ChannelWithMeta channel : channelIDs) {
+			AbstractChannelReaderInputView view = FileChannelUtil.createInputView(
+					ioManager, channel, openChannels, compressionEnable, compressionCodecFactory,
+					compressionBlockSize, pageSize);
+			iterators.add(channelReaderInputViewIterator(view));
+		}
+
+		return new BinaryMergeIterator<>(
+				iterators, mergeReusedEntries(channelIDs.size()), mergeComparator());
+	}
+
+	/**
+	 * Merges the given sorted runs to a smaller number of sorted runs.
+	 *
+	 * @param channelIDs     The IDs of the sorted runs that need to be merged.
+	 * @return A list of the IDs of the merged channels.
+	 * @throws IOException Thrown, if the readers or writers encountered an I/O problem.
+	 */
+	public List<ChannelWithMeta> mergeChannelList(List<ChannelWithMeta> channelIDs) throws IOException {
+		// A channel list with length maxFanIn<sup>i</sup> can be merged to maxFanIn files in i-1 rounds where every merge
+		// is a full merge with maxFanIn input channels. A partial round includes merges with fewer than maxFanIn
+		// inputs. It is most efficient to perform the partial round first.
+		final double scale = Math.ceil(Math.log(channelIDs.size()) / Math.log(maxFanIn)) - 1;
+
+		final int numStart = channelIDs.size();
+		final int numEnd = (int) Math.pow(maxFanIn, scale);
+
+		final int numMerges = (int) Math.ceil((numStart - numEnd) / (double) (maxFanIn - 1));
+
+		final int numNotMerged = numEnd - numMerges;
+		final int numToMerge = numStart - numNotMerged;
+
+		// unmerged channel IDs are copied directly to the result list
+		final List<ChannelWithMeta> mergedChannelIDs = new ArrayList<>(numEnd);
+		mergedChannelIDs.addAll(channelIDs.subList(0, numNotMerged));
+
+		final int channelsToMergePerStep = (int) Math.ceil(numToMerge / (double) numMerges);
+
+		final List<ChannelWithMeta> channelsToMergeThisStep = new ArrayList<>(channelsToMergePerStep);
+		int channelNum = numNotMerged;
+		while (!closed && channelNum < channelIDs.size()) {
+			channelsToMergeThisStep.clear();
+
+			for (int i = 0; i < channelsToMergePerStep && channelNum < channelIDs.size(); i++, channelNum++) {
+				channelsToMergeThisStep.add(channelIDs.get(channelNum));
+			}
+
+			mergedChannelIDs.add(mergeChannels(channelsToMergeThisStep));
+		}
+
+		return mergedChannelIDs;
+	}
+
+	/**
+	 * Merges the sorted runs described by the given Channel IDs into a single sorted run.
+	 *
+	 * @param channelIDs   The IDs of the runs' channels.
+	 * @return The ID and number of blocks of the channel that describes the merged run.
+	 */
+	private ChannelWithMeta mergeChannels(List<ChannelWithMeta> channelIDs) throws IOException {
+		// the list with the target iterators
+		List<FileIOChannel> openChannels = new ArrayList<>(channelIDs.size());
+		final BinaryMergeIterator<Entry> mergeIterator =
+				getMergingIterator(channelIDs, openChannels);
+
+		// create a new channel writer
+		final FileIOChannel.ID mergedChannelID = ioManager.createChannel();
+		channelManager.addChannel(mergedChannelID);
+		AbstractChannelWriterOutputView output = null;
+
+		int numBytesInLastBlock;
+		int numBlocksWritten;
+		try {
+			output = FileChannelUtil.createOutputView(
+					ioManager, mergedChannelID, compressionEnable,
+					compressionCodecFactory, compressionBlockSize, pageSize);
+			writeMergingOutput(mergeIterator, output);
+			numBytesInLastBlock = output.close();
+			numBlocksWritten = output.getBlockCount();
+		} catch (IOException e) {
+			if (output != null) {
+				output.close();
+				output.getChannel().deleteChannel();
+			}
+			throw e;
+		}
+
+		// remove, close and delete channels
+		for (FileIOChannel channel : openChannels) {
+			channelManager.removeChannel(channel.getChannelID());
+			try {
+				channel.closeAndDelete();
+			} catch (Throwable ignored) {
+			}
+		}
+
+		return new ChannelWithMeta(mergedChannelID, numBlocksWritten, numBytesInLastBlock);
+	}
+
+	// -------------------------------------------------------------------------------------------
+
+	/**
+	 * @return entry iterator reading from inView.
+	 */
+	protected abstract MutableObjectIterator<Entry> channelReaderInputViewIterator(
+			AbstractChannelReaderInputView inView);
+
+	/**
+	 * @return merging comparator used in merging.
+	 */
+	protected abstract Comparator<Entry> mergeComparator();
+
+	/**
+	 * @return reused entry object used in merging.
+	 */
+	protected abstract List<Entry> mergeReusedEntries(int size);
+
+	/**
+	 * read the merged stream and write the data back.
+	 */
+	protected abstract void writeMergingOutput(
+			MutableObjectIterator<Entry> mergeIterator,
+			AbstractPagedOutputView output) throws IOException;
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BinaryExternalMerger.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BinaryExternalMerger.java
new file mode 100644
index 0000000..366d822
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BinaryExternalMerger.java
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.runtime.io.disk.ChannelReaderInputViewIterator;
+import org.apache.flink.runtime.io.disk.iomanager.AbstractChannelReaderInputView;
+import org.apache.flink.runtime.io.disk.iomanager.IOManager;
+import org.apache.flink.runtime.memory.AbstractPagedOutputView;
+import org.apache.flink.table.dataformat.BinaryRow;
+import org.apache.flink.table.runtime.compression.BlockCompressionFactory;
+import org.apache.flink.table.typeutils.BinaryRowSerializer;
+import org.apache.flink.util.MutableObjectIterator;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+
+/**
+ * Record merger for sort of BinaryRow.
+ */
+public class BinaryExternalMerger extends AbstractBinaryExternalMerger<BinaryRow> {
+
+	private final BinaryRowSerializer serializer;
+	private final RecordComparator comparator;
+
+	public BinaryExternalMerger(
+			IOManager ioManager,
+			int pageSize,
+			int maxFanIn,
+			SpillChannelManager channelManager,
+			BinaryRowSerializer serializer,
+			RecordComparator comparator,
+			boolean compressionEnable,
+			BlockCompressionFactory compressionCodecFactory,
+			int compressionBlockSize) {
+		super(ioManager, pageSize, maxFanIn, channelManager, compressionEnable, compressionCodecFactory, compressionBlockSize);
+		this.serializer = serializer;
+		this.comparator = comparator;
+	}
+
+	@Override
+	protected MutableObjectIterator<BinaryRow> channelReaderInputViewIterator(AbstractChannelReaderInputView inView) {
+		return new ChannelReaderInputViewIterator<>(inView, null, serializer.duplicate());
+	}
+
+	@Override
+	protected Comparator<BinaryRow> mergeComparator() {
+		return comparator::compare;
+	}
+
+	@Override
+	protected List<BinaryRow> mergeReusedEntries(int size) {
+		ArrayList<BinaryRow> reused = new ArrayList<>(size);
+		for (int i = 0; i < size; i++) {
+			reused.add(serializer.createInstance());
+		}
+		return reused;
+	}
+
+	@Override
+	protected void writeMergingOutput(
+			MutableObjectIterator<BinaryRow> mergeIterator,
+			AbstractPagedOutputView output) throws IOException {
+		// read the merged stream and write the data back
+		BinaryRow rec = serializer.createInstance();
+		while ((rec = mergeIterator.next(rec)) != null) {
+			serializer.serialize(rec, output);
+		}
+	}
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BinaryExternalSorter.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BinaryExternalSorter.java
new file mode 100644
index 0000000..d04f0ae
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BinaryExternalSorter.java
@@ -0,0 +1,1168 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.configuration.AlgorithmOptions;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.core.memory.MemorySegment;
+import org.apache.flink.runtime.io.disk.iomanager.AbstractChannelWriterOutputView;
+import org.apache.flink.runtime.io.disk.iomanager.FileIOChannel;
+import org.apache.flink.runtime.io.disk.iomanager.IOManager;
+import org.apache.flink.runtime.memory.MemoryAllocationException;
+import org.apache.flink.runtime.memory.MemoryManager;
+import org.apache.flink.runtime.operators.sort.ExceptionHandler;
+import org.apache.flink.runtime.operators.sort.IndexedSorter;
+import org.apache.flink.runtime.operators.sort.QuickSort;
+import org.apache.flink.runtime.operators.sort.Sorter;
+import org.apache.flink.runtime.util.EmptyMutableObjectIterator;
+import org.apache.flink.table.api.TableConfigOptions;
+import org.apache.flink.table.dataformat.BaseRow;
+import org.apache.flink.table.dataformat.BinaryRow;
+import org.apache.flink.table.runtime.compression.BlockCompressionFactory;
+import org.apache.flink.table.runtime.io.ChannelWithMeta;
+import org.apache.flink.table.runtime.util.FileChannelUtil;
+import org.apache.flink.table.typeutils.AbstractRowSerializer;
+import org.apache.flink.table.typeutils.BinaryRowSerializer;
+import org.apache.flink.util.MutableObjectIterator;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Queue;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+
+import static org.apache.flink.util.Preconditions.checkArgument;
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+/**
+ * The {@link BinaryExternalSorter} is a full fledged sorter for binary format.
+ * It implements a multi-way merge sort.
+ * Internally, it has three asynchronous threads (sort, spill, merger) which communicate through
+ * a set of blocking circularQueues, forming a closed loop. Memory is allocated using the
+ * {@link MemoryManager} interface. Thus the component will not exceed the provided memory limits.
+ */
+public class BinaryExternalSorter implements Sorter<BinaryRow> {
+
+	// ------------------------------------------------------------------------
+	//                              Constants
+	// ------------------------------------------------------------------------
+
+	/** The minimum number of segments that are required for the sort to operate. */
+	private static final int MIN_NUM_SORT_MEM_SEGMENTS = 10;
+
+	private static final long SORTER_MIN_NUM_SORT_MEM =
+			MIN_NUM_SORT_MEM_SEGMENTS * MemoryManager.DEFAULT_PAGE_SIZE;
+
+	/** Logging. */
+	private static final Logger LOG = LoggerFactory.getLogger(BinaryExternalSorter.class);
+
+	// ------------------------------------------------------------------------
+	//                                  Threads
+	// ------------------------------------------------------------------------
+
+	/**
+	 * The currWriteBuffer that is passed as marker for the end of data.
+	 */
+	private static final CircularElement EOF_MARKER = new CircularElement();
+
+	/**
+	 * The currWriteBuffer that is passed as marker for signaling the beginning of spilling.
+	 */
+	private static final CircularElement SPILLING_MARKER = new CircularElement();
+
+	/**
+	 * The ChannelWithMeta that is passed as marker for signaling the final merge.
+	 */
+	private static final ChannelWithMeta FINAL_MERGE_MARKER = new ChannelWithMeta(null, -1, -1);
+
+	// ------------------------------------------------------------------------
+	//                                   Memory
+	// ------------------------------------------------------------------------
+
+	/**
+	 * The memory segments used first for sorting and later for reading/pre-fetching
+	 * during the external merge.
+	 */
+	private final List<List<MemorySegment>> sortReadMemory;
+
+	/**
+	 * Records all sort buffer.
+	 */
+	private final List<BinaryInMemorySortBuffer> sortBuffers;
+
+	/** The memory manager through which memory is allocated and released. */
+	private final MemoryManager memoryManager;
+
+	// ------------------------------------------------------------------------
+	//                            Miscellaneous Fields
+	// ------------------------------------------------------------------------
+
+	/**
+	 * The monitor which guards the iterator field.
+	 */
+	private final Object iteratorLock = new Object();
+
+	/** The thread that merges the buffer handed from the reading thread. */
+	private ThreadBase sortThread;
+
+	/** The thread that handles spilling to secondary storage. */
+	private ThreadBase spillThread;
+
+	/** The thread that handles merging from the secondary storage. */
+	private ThreadBase mergeThread;
+
+	/**
+	 * Final result iterator.
+	 */
+	private volatile MutableObjectIterator<BinaryRow> iterator;
+
+	/**
+	 * The exception that is set, if the iterator cannot be created.
+	 */
+	private volatile IOException iteratorException;
+
+	/**
+	 * Flag indicating that the sorter was closed.
+	 */
+	private volatile boolean closed;
+
+	/**
+	 * Sort or spill thread maybe occur some exceptions.
+	 */
+	private ExceptionHandler<IOException> exceptionHandler;
+
+	/**
+	 * Queue for the communication between the threads.
+	 */
+	private CircularQueues circularQueues;
+
+	private long bytesUntilSpilling;
+
+	private CircularElement currWriteBuffer;
+
+	private boolean writingDone = false;
+
+	private final Object writeLock = new Object();
+
+	private final SpillChannelManager channelManager;
+
+	private final BinaryExternalMerger merger;
+
+	private final int memorySegmentSize;
+
+	private final boolean compressionEnable;
+	private final BlockCompressionFactory compressionCodecFactory;
+	private final int compressionBlockSize;
+
+	private final boolean asyncMergeEnable;
+
+	// ------------------------------------------------------------------------
+	//                         Constructor & Shutdown
+	// ------------------------------------------------------------------------
+
+	private final BinaryRowSerializer serializer;
+
+	//metric
+	private long numSpillFiles;
+	private long spillInBytes;
+	private long spillInCompressedBytes;
+
+	public BinaryExternalSorter(
+			final Object owner, MemoryManager memoryManager, long reservedMemorySize,
+			IOManager ioManager, AbstractRowSerializer<BaseRow> inputSerializer,
+			BinaryRowSerializer serializer, NormalizedKeyComputer normalizedKeyComputer,
+			RecordComparator comparator, Configuration conf) throws IOException {
+		this(owner, memoryManager, reservedMemorySize, ioManager,
+				inputSerializer, serializer, normalizedKeyComputer, comparator,
+				conf, AlgorithmOptions.SORT_SPILLING_THRESHOLD.defaultValue());
+	}
+
+	public BinaryExternalSorter(
+			final Object owner, MemoryManager memoryManager, long reservedMemorySize,
+			IOManager ioManager, AbstractRowSerializer<BaseRow> inputSerializer,
+			BinaryRowSerializer serializer,
+			NormalizedKeyComputer normalizedKeyComputer,
+			RecordComparator comparator, Configuration conf,
+			float startSpillingFraction) throws IOException {
+		int maxNumFileHandles = conf.getInteger(TableConfigOptions.SQL_EXEC_SORT_FILE_HANDLES_MAX_NUM);
+		this.compressionEnable = conf.getBoolean(TableConfigOptions.SQL_EXEC_SPILL_COMPRESSION_ENABLED);
+		this.compressionCodecFactory = this.compressionEnable
+			? BlockCompressionFactory.createBlockCompressionFactory(
+					conf.getString(TableConfigOptions.SQL_EXEC_SPILL_COMPRESSION_CODEC))
+			: null;
+		compressionBlockSize = conf.getInteger(TableConfigOptions.SQL_EXEC_SPILL_COMPRESSION_BLOCK_SIZE);
+		asyncMergeEnable = conf.getBoolean(TableConfigOptions.SQL_EXEC_SORT_ASYNC_MERGE_ENABLED);
+
+		checkArgument(maxNumFileHandles >= 2);
+		checkNotNull(ioManager);
+		checkNotNull(normalizedKeyComputer);
+		this.serializer = (BinaryRowSerializer) serializer.duplicate();
+		this.memoryManager = checkNotNull(memoryManager);
+		this.memorySegmentSize = memoryManager.getPageSize();
+
+		if (reservedMemorySize < SORTER_MIN_NUM_SORT_MEM) {
+			throw new IllegalArgumentException("Too little memory provided to sorter to perform task. " +
+					"Required are at least " + SORTER_MIN_NUM_SORT_MEM +
+					" pages. Current page size is " + memoryManager.getPageSize() + " bytes.");
+		}
+
+		// adjust the memory quotas to the page size
+		final int sortMemPages = (int) (reservedMemorySize / memoryManager.getPageSize());
+		final long sortMemory = ((long) sortMemPages) * memoryManager.getPageSize();
+
+		// decide how many sort buffers to use
+		int numSortBuffers = 1;
+		if (reservedMemorySize > 100 * 1024 * 1024L) {
+			numSortBuffers = 2;
+		}
+		final int numSegmentsPerSortBuffer = sortMemPages / numSortBuffers;
+		this.sortReadMemory = new ArrayList<>();
+		List<MemorySegment> readMemory;
+		try {
+			readMemory = memoryManager.allocatePages(owner, sortMemPages);
+		} catch (MemoryAllocationException e) {
+			LOG.error("Can't allocate {} pages from fixed memory pool.", sortMemPages, e);
+			throw new RuntimeException(e);
+		}
+
+		// circular circularQueues pass buffers between the threads
+		final CircularQueues circularQueues = new CircularQueues();
+
+		// allocate the sort buffers and fill empty queue with them
+		final Iterator<MemorySegment> segments = readMemory.iterator();
+
+		LOG.info("BinaryExternalSorter with initial memory segments {}, " +
+				"maxNumFileHandles({}), compressionEnable({}), compressionCodecFactory({}), compressionBlockSize({}).",
+				sortMemPages, maxNumFileHandles, compressionEnable,
+				compressionEnable ? compressionCodecFactory.getClass() : null, compressionBlockSize);
+
+		this.sortBuffers = new ArrayList<>();
+		for (int i = 0; i < numSortBuffers; i++) {
+			// grab some memory
+			final List<MemorySegment> sortSegments = new ArrayList<>(numSegmentsPerSortBuffer);
+			for (int k = (i == numSortBuffers - 1 ? Integer.MAX_VALUE : numSegmentsPerSortBuffer); k > 0 && segments
+					.hasNext(); k--) {
+				sortSegments.add(segments.next());
+			}
+			this.sortReadMemory.add(sortSegments);
+			final BinaryInMemorySortBuffer buffer = BinaryInMemorySortBuffer.createBuffer(
+					normalizedKeyComputer, inputSerializer, serializer, comparator, sortSegments);
+
+			// add to empty queue
+			CircularElement element = new CircularElement(i, buffer, sortSegments);
+			circularQueues.empty.add(element);
+			this.sortBuffers.add(buffer);
+		}
+
+		// exception handling
+		ExceptionHandler<IOException> exceptionHandler = exception -> {
+			// forward exception
+			if (!closed) {
+				setResultIteratorException(exception);
+				close();
+			}
+		};
+
+		// init adding currWriteBuffer
+		this.exceptionHandler = exceptionHandler;
+		this.circularQueues = circularQueues;
+
+		bytesUntilSpilling = ((long) (startSpillingFraction * sortMemory));
+
+		// check if we should directly spill
+		if (bytesUntilSpilling < 1) {
+			bytesUntilSpilling = 0;
+			// add the spilling marker
+			this.circularQueues.sort.add(SPILLING_MARKER);
+		}
+
+		this.channelManager = new SpillChannelManager();
+		this.merger = new BinaryExternalMerger(
+				ioManager, memoryManager.getPageSize(),
+				maxNumFileHandles, channelManager,
+				(BinaryRowSerializer) serializer.duplicate(), comparator,
+				compressionEnable, compressionCodecFactory, compressionBlockSize);
+
+		// start the thread that sorts the buffers
+		this.sortThread = getSortingThread(exceptionHandler, circularQueues);
+
+		// start the thread that handles spilling to secondary storage
+		this.spillThread = getSpillingThread(
+				exceptionHandler, circularQueues, ioManager,
+				(BinaryRowSerializer) serializer.duplicate(), comparator);
+
+		// start the thread that handles merging from second storage
+		this.mergeThread = getMergingThread(
+			exceptionHandler, circularQueues, ioManager, maxNumFileHandles, merger);
+
+		// propagate the context class loader to the spawned threads
+		ClassLoader contextLoader = Thread.currentThread().getContextClassLoader();
+		if (contextLoader != null) {
+			if (this.sortThread != null) {
+				this.sortThread.setContextClassLoader(contextLoader);
+			}
+			if (this.spillThread != null) {
+				this.spillThread.setContextClassLoader(contextLoader);
+			}
+			if (this.mergeThread != null) {
+				this.mergeThread.setContextClassLoader(contextLoader);
+			}
+		}
+	}
+
+	// ------------------------------------------------------------------------
+	//                           Factory Methods
+	// ------------------------------------------------------------------------
+
+	/**
+	 * Starts all the threads that are used by this sorter.
+	 */
+	public void startThreads() {
+		if (this.sortThread != null) {
+			this.sortThread.start();
+		}
+		if (this.spillThread != null) {
+			this.spillThread.start();
+		}
+		if (this.mergeThread != null) {
+			this.mergeThread.start();
+		}
+	}
+
+	/**
+	 * Shuts down all the threads initiated by this sorter. Also releases all previously allocated
+	 * memory, if it has not yet been released by the threads, and closes and deletes all channels
+	 * (removing the temporary files).
+	 *
+	 * <p>The threads are set to exit directly, but depending on their operation, it may take a
+	 * while to actually happen. The sorting thread will for example not finish before the current
+	 * batch is sorted. This method attempts to wait for the working thread to exit. If it is
+	 * however interrupted, the method exits immediately and is not guaranteed how long the threads
+	 * continue to exist and occupy resources afterwards.
+	 */
+	@Override
+	public void close() {
+		// check if the sorter has been closed before
+		synchronized (this) {
+			if (this.closed) {
+				return;
+			}
+
+			// mark as closed
+			this.closed = true;
+		}
+
+		// from here on, the code is in a try block, because even through errors might be thrown in this block,
+		// we need to make sure that all the memory is released.
+		try {
+			// if the result iterator has not been obtained yet, set the exception
+			synchronized (this.iteratorLock) {
+				if (this.iteratorException == null) {
+					this.iteratorException = new IOException("The sorter has been closed.");
+					this.iteratorLock.notifyAll();
+				}
+			}
+
+			// stop all the threads
+			if (this.sortThread != null) {
+				try {
+					this.sortThread.shutdown();
+				} catch (Throwable t) {
+					LOG.error("Error shutting down sorter thread: " + t.getMessage(), t);
+				}
+			}
+			if (this.spillThread != null) {
+				try {
+					this.spillThread.shutdown();
+				} catch (Throwable t) {
+					LOG.error("Error shutting down spilling thread: " + t.getMessage(), t);
+				}
+			}
+			if (this.mergeThread != null) {
+				try {
+					this.mergeThread.shutdown();
+				} catch (Throwable t) {
+					LOG.error("Error shutting down merging thread: " + t.getMessage(), t);
+				}
+			}
+
+			try {
+				if (this.sortThread != null) {
+					this.sortThread.join();
+					this.sortThread = null;
+				}
+				if (this.spillThread != null) {
+					this.spillThread.join();
+					this.spillThread = null;
+				}
+				if (this.mergeThread != null) {
+					this.mergeThread.join();
+					this.mergeThread = null;
+				}
+			} catch (InterruptedException iex) {
+				LOG.debug("Closing of sort/merger was interrupted. " +
+						"The reading/sorting/spilling/merging threads may still be working.", iex);
+			}
+		} finally {
+			releaseSortMemory();
+
+			// Eliminate object references for MemorySegments.
+			circularQueues = null;
+			currWriteBuffer = null;
+			iterator = null;
+
+			merger.close();
+			channelManager.close();
+		}
+	}
+
+	private void releaseSortMemory() {
+		// RELEASE ALL MEMORY. If the threads and channels are still running, this should cause
+		// exceptions, because their memory segments are freed
+
+		try {
+			// floating segments are released in `dispose()` method
+			this.sortBuffers.forEach(BinaryInMemorySortBuffer::dispose);
+			this.sortBuffers.clear();
+		} catch (Throwable ignored) {
+			LOG.info("error.", ignored);
+		}
+
+		releaseCoreSegments();
+		sortReadMemory.clear();
+	}
+
+	private void releaseCoreSegments() {
+		// NOTE: This method can only be called after disposing some buffers
+
+		List<MemorySegment> coreSegments = new ArrayList<>();
+		for (List<MemorySegment> segs : sortReadMemory) {
+			coreSegments.addAll(segs);
+		}
+
+		try {
+			if (!coreSegments.isEmpty()) {
+				this.memoryManager.release(coreSegments);
+			}
+			coreSegments.clear();
+		} catch (Throwable ignored) {
+			LOG.info("error.", ignored);
+		}
+	}
+
+	private ThreadBase getSortingThread(ExceptionHandler<IOException> exceptionHandler,
+			CircularQueues queues) {
+		return new SortingThread(exceptionHandler, queues);
+	}
+
+	private SpillingThread getSpillingThread(ExceptionHandler<IOException> exceptionHandler,
+			CircularQueues queues, IOManager ioManager,
+			BinaryRowSerializer serializer, RecordComparator comparator) {
+		return new SpillingThread(exceptionHandler, queues, ioManager, serializer, comparator);
+	}
+
+	private MergingThread getMergingThread(
+			ExceptionHandler<IOException> exceptionHandler,
+			CircularQueues queues, IOManager ioManager,
+			int maxNumFileHandles, BinaryExternalMerger merger) {
+		return new MergingThread(exceptionHandler, queues, ioManager, maxNumFileHandles, merger);
+	}
+
+	public void write(BaseRow current) throws IOException {
+		checkArgument(!writingDone, "Adding already done!");
+		try {
+			while (true) {
+				if (closed) {
+					throw new IOException("Already closed!", iteratorException);
+				}
+
+				synchronized (writeLock) {
+					// grab the next buffer
+					if (currWriteBuffer == null) {
+						try {
+							currWriteBuffer = this.circularQueues.empty.poll(1, TimeUnit.SECONDS);
+							if (currWriteBuffer == null) {
+								// maybe something happened, release lock.
+								continue;
+							}
+							if (!currWriteBuffer.buffer.isEmpty()) {
+								throw new IOException("New buffer is not empty.");
+							}
+						} catch (InterruptedException iex) {
+							throw new IOException(iex);
+						}
+					}
+
+					final BinaryInMemorySortBuffer buffer = currWriteBuffer.buffer;
+
+					if (LOG.isDebugEnabled()) {
+						LOG.debug("Retrieved empty read buffer " + currWriteBuffer.id + ".");
+					}
+
+					long occupancy = buffer.getOccupancy();
+					if (!buffer.write(current)) {
+						if (buffer.isEmpty()) {
+							// did not fit in a fresh buffer, must be large...
+							throw new IOException("The record exceeds the maximum size of a sort buffer (current maximum: "
+									+ buffer.getCapacity() + " bytes).");
+						} else {
+							// buffer is full, send the buffer
+							if (LOG.isDebugEnabled()) {
+								LOG.debug("Emitting full buffer: " + currWriteBuffer.id + ".");
+							}
+
+							this.circularQueues.sort.add(currWriteBuffer);
+
+							// Deadlocks may occur when there are fewer MemorySegments, because of
+							// the fragmentation of buffer.getOccupancy ().
+							if (bytesUntilSpilling > 0 && circularQueues.empty.size() == 0) {
+								bytesUntilSpilling = 0;
+								this.circularQueues.sort.add(SPILLING_MARKER);
+							}
+
+							currWriteBuffer = null;
+							// continue to process current record.
+						}
+					} else {
+						// successfully added record
+						// it may be that the last currWriteBuffer would have crossed the
+						// spilling threshold, so check it
+						if (bytesUntilSpilling > 0) {
+							bytesUntilSpilling -= buffer.getOccupancy() - occupancy;
+							if (bytesUntilSpilling <= 0) {
+								bytesUntilSpilling = 0;
+								this.circularQueues.sort.add(SPILLING_MARKER);
+							}
+						}
+						break;
+					}
+				}
+			}
+		} catch (Throwable e) {
+			IOException ioe = new IOException(e);
+			if (this.exceptionHandler != null) {
+				this.exceptionHandler.handleException(ioe);
+			}
+			throw ioe;
+		}
+	}
+
+	@VisibleForTesting
+	public void write(MutableObjectIterator<BinaryRow> iterator) throws IOException {
+		BinaryRow row = serializer.createInstance();
+		while ((row = iterator.next(row)) != null) {
+			write(row);
+		}
+	}
+
+	@Override
+	public MutableObjectIterator<BinaryRow> getIterator() throws InterruptedException {
+		if (!writingDone) {
+			writingDone = true;
+
+			if (currWriteBuffer != null) {
+				this.circularQueues.sort.add(currWriteBuffer);
+			}
+
+			// add the sentinel to notify the receivers that the work is done
+			// send the EOF marker
+			this.circularQueues.sort.add(EOF_MARKER);
+			LOG.debug("Sending done.");
+		}
+
+		synchronized (this.iteratorLock) {
+			// wait while both the iterator and the exception are not set
+			while (this.iterator == null && this.iteratorException == null) {
+				this.iteratorLock.wait();
+			}
+
+			if (this.iteratorException != null) {
+				throw new RuntimeException("Error obtaining the sorted input: " + this.iteratorException.getMessage(),
+						this.iteratorException);
+			} else {
+				return this.iterator;
+			}
+		}
+	}
+
+	// ------------------------------------------------------------------------
+	// Inter-Thread Communication
+	// ------------------------------------------------------------------------
+
+	/**
+	 * Sets the result iterator. By setting the result iterator, all threads that are waiting for
+	 * the result
+	 * iterator are notified and will obtain it.
+	 *
+	 * @param iterator The result iterator to set.
+	 */
+	private void setResultIterator(MutableObjectIterator<BinaryRow> iterator) {
+		synchronized (this.iteratorLock) {
+			// set the result iterator only, if no exception has occurred
+			if (this.iteratorException == null) {
+				this.iterator = iterator;
+				this.iteratorLock.notifyAll();
+			}
+		}
+	}
+
+	/**
+	 * Reports an exception to all threads that are waiting for the result iterator.
+	 *
+	 * @param ioex The exception to be reported to the threads that wait for the result iterator.
+	 */
+	private void setResultIteratorException(IOException ioex) {
+		synchronized (this.iteratorLock) {
+			if (this.iteratorException == null) {
+				this.iteratorException = ioex;
+				this.iteratorLock.notifyAll();
+			}
+		}
+	}
+
+	/**
+	 * Class representing buffers that circulate between the reading, sorting and spilling thread.
+	 */
+	private static final class CircularElement {
+
+		final int id; // just for debug.
+		final BinaryInMemorySortBuffer buffer;
+		final List<MemorySegment> memory; // for release memory
+
+		public CircularElement() {
+			this.id = -1;
+			this.buffer = null;
+			this.memory = null;
+		}
+
+		public CircularElement(int id, BinaryInMemorySortBuffer buffer, List<MemorySegment> memory) {
+			this.id = id;
+			this.buffer = buffer;
+			this.memory = memory;
+		}
+	}
+
+	/**
+	 * Collection of circularQueues that are used for the communication between the threads.
+	 */
+	private static final class CircularQueues {
+
+		final BlockingQueue<CircularElement> empty;
+
+		final BlockingQueue<CircularElement> sort;
+
+		final BlockingQueue<CircularElement> spill;
+
+		final BlockingQueue<ChannelWithMeta> merge;
+
+		private CircularQueues() {
+			this.empty = new LinkedBlockingQueue<>();
+			this.sort = new LinkedBlockingQueue<>();
+			this.spill = new LinkedBlockingQueue<>();
+			this.merge = new LinkedBlockingQueue<>();
+		}
+	}
+
+	// ------------------------------------------------------------------------
+	// Threads
+	// ------------------------------------------------------------------------
+
+	/**
+	 * Base class for all working threads in this sorter. The specific threads for sorting,
+	 * spilling, etc... extend this subclass.
+	 *
+	 * <p>The threads are designed to terminate themselves when the task they are set up to do is
+	 * completed. Further more, they terminate immediately when the <code>shutdown()</code> method
+	 * is called.
+	 */
+	private abstract static class ThreadBase extends Thread implements Thread.UncaughtExceptionHandler {
+
+		/**
+		 * The queue of empty buffer that can be used for reading.
+		 */
+		final CircularQueues queues;
+
+		/**
+		 * The exception handler for any problems.
+		 */
+		private final ExceptionHandler<IOException> exceptionHandler;
+
+		/**
+		 * The flag marking this thread as alive.
+		 */
+		private volatile boolean alive;
+
+		/**
+		 * Creates a new thread.
+		 *
+		 * @param exceptionHandler The exception handler to call for all exceptions.
+		 * @param name             The name of the thread.
+		 * @param queues           The circularQueues used to pass buffers between the threads.
+		 */
+		private ThreadBase(ExceptionHandler<IOException> exceptionHandler, String name,
+				CircularQueues queues) {
+			// thread setup
+			super(name);
+			this.setDaemon(true);
+
+			// exception handling
+			this.exceptionHandler = exceptionHandler;
+			this.setUncaughtExceptionHandler(this);
+
+			this.queues = queues;
+			this.alive = true;
+		}
+
+		/**
+		 * Implements exception handling and delegates to go().
+		 */
+		public void run() {
+			try {
+				go();
+			} catch (Throwable t) {
+				internalHandleException(new IOException("Thread '" + getName() + "' terminated due to an exception: "
+						+ t.getMessage(), t));
+			}
+		}
+
+		/**
+		 * Equivalent to the run() method.
+		 *
+		 * @throws IOException Exceptions that prohibit correct completion of the work may be thrown
+		 *                     by the thread.
+		 */
+		abstract void go() throws IOException;
+
+		/**
+		 * Checks whether this thread is still alive.
+		 *
+		 * @return true, if the thread is alive, false otherwise.
+		 */
+		public boolean isRunning() {
+			return this.alive;
+		}
+
+		/**
+		 * Forces an immediate shutdown of the thread. Looses any state and all buffers that the
+		 * thread is currently
+		 * working on. This terminates cleanly for the JVM, but looses intermediate results.
+		 */
+		public void shutdown() {
+			this.alive = false;
+			this.interrupt();
+		}
+
+		/**
+		 * Internally handles an exception and makes sure that this method returns without a
+		 * problem.
+		 *
+		 * @param ioex The exception to handle.
+		 */
+		private void internalHandleException(IOException ioex) {
+			if (!isRunning()) {
+				// discard any exception that occurs when after the thread is killed.
+				return;
+			}
+			if (this.exceptionHandler != null) {
+				try {
+					this.exceptionHandler.handleException(ioex);
+				} catch (Throwable ignored) {
+				}
+			}
+		}
+
+		@Override
+		public void uncaughtException(Thread t, Throwable e) {
+			internalHandleException(new IOException("Thread '" + t.getName()
+					+ "' terminated due to an uncaught exception: " + e.getMessage(), e));
+		}
+	}
+
+	/**
+	 * The thread that sorts filled buffers.
+	 */
+	private static class SortingThread extends ThreadBase {
+
+		private final IndexedSorter sorter;
+
+		/**
+		 * Creates a new sorting thread.
+		 *
+		 * @param exceptionHandler The exception handler to call for all exceptions.
+		 * @param queues           The circularQueues used to pass buffers between the threads.
+		 */
+		public SortingThread(ExceptionHandler<IOException> exceptionHandler,
+				CircularQueues queues) {
+			super(exceptionHandler, "SortMerger sorting thread", queues);
+
+			// members
+			this.sorter = new QuickSort();
+		}
+
+		/**
+		 * Entry point of the thread.
+		 */
+		public void go() throws IOException {
+			boolean alive = true;
+
+			// loop as long as the thread is marked alive
+			while (isRunning() && alive) {
+				CircularElement element;
+				try {
+					element = this.queues.sort.take();
+				} catch (InterruptedException iex) {
+					if (isRunning()) {
+						if (LOG.isErrorEnabled()) {
+							LOG.error(
+									"Sorting thread was interrupted (without being shut down) while grabbing a buffer. " +
+											"Retrying to grab buffer...");
+						}
+						continue;
+					} else {
+						return;
+					}
+				}
+
+				if (element != EOF_MARKER && element != SPILLING_MARKER) {
+
+					if (element.buffer.size() == 0) {
+						element.buffer.reset();
+						this.queues.empty.add(element);
+						continue;
+					}
+
+					if (LOG.isDebugEnabled()) {
+						LOG.debug("Sorting buffer " + element.id + ".");
+					}
+
+					this.sorter.sort(element.buffer);
+
+					if (LOG.isDebugEnabled()) {
+						LOG.debug("Sorted buffer " + element.id + ".");
+					}
+				} else if (element == EOF_MARKER) {
+					if (LOG.isDebugEnabled()) {
+						LOG.debug("Sorting thread done.");
+					}
+					alive = false;
+				}
+				this.queues.spill.add(element);
+			}
+		}
+	}
+
+	/**
+	 * The thread that handles the spilling of intermediate results.
+	 */
+	private class SpillingThread extends ThreadBase {
+
+		private final IOManager ioManager;                // I/O manager to create channels
+
+		private final BinaryRowSerializer serializer;     // The serializer for the data type
+
+		private final RecordComparator comparator;
+
+		/**
+		 * Creates the spilling thread.
+		 * @param exceptionHandler  The exception handler to call for all exceptions.
+		 * @param queues            The circularQueues used to pass buffers between the threads.
+		 * @param ioManager         The I/O manager used to instantiate readers and writers from.
+		 * @param serializer
+		 * @param comparator
+		 */
+		public SpillingThread(ExceptionHandler<IOException> exceptionHandler,
+				CircularQueues queues, IOManager ioManager,
+				BinaryRowSerializer serializer, RecordComparator comparator) {
+			super(exceptionHandler, "SortMerger spilling thread", queues);
+			this.ioManager = ioManager;
+			this.serializer = serializer;
+			this.comparator = comparator;
+		}
+
+		/**
+		 * Entry point of the thread.
+		 */
+		public void go() throws IOException {
+
+			final Queue<CircularElement> cache = new ArrayDeque<>();
+			CircularElement element;
+			boolean cacheOnly = false;
+
+			// ------------------- In-Memory Cache ------------------------
+			// fill cache
+			while (isRunning()) {
+				// take next currWriteBuffer from queue
+				try {
+					element = this.queues.spill.take();
+				} catch (InterruptedException iex) {
+					throw new IOException("The spilling thread was interrupted.");
+				}
+
+				if (element == SPILLING_MARKER) {
+					break;
+				} else if (element == EOF_MARKER) {
+					cacheOnly = true;
+					break;
+				}
+				cache.add(element);
+			}
+
+			// check whether the thread was canceled
+			if (!isRunning()) {
+				return;
+			}
+
+			// ------------------- In-Memory Merge ------------------------
+			if (cacheOnly) {
+				List<MutableObjectIterator<BinaryRow>> iterators = new ArrayList<>(cache.size());
+
+				for (CircularElement cached : cache) {
+					iterators.add(cached.buffer.getIterator());
+				}
+
+				// set lazy iterator
+				List<BinaryRow> reusableEntries = new ArrayList<>();
+				for (int i = 0; i < iterators.size(); i++) {
+					reusableEntries.add(serializer.createInstance());
+				}
+				setResultIterator(iterators.isEmpty() ? EmptyMutableObjectIterator.get() :
+						iterators.size() == 1 ? iterators.get(0) : new BinaryMergeIterator<>(
+								iterators, reusableEntries, comparator::compare));
+
+				releaseEmptyBuffers();
+
+				// signal merging thread to exit (because there is nothing to merge externally)
+				this.queues.merge.add(FINAL_MERGE_MARKER);
+
+				return;
+			}
+
+			// ------------------- Spilling Phase ------------------------
+
+			final FileIOChannel.Enumerator enumerator =
+					this.ioManager.createChannelEnumerator();
+
+			// loop as long as the thread is marked alive and we do not see the final currWriteBuffer
+			while (isRunning()) {
+				try {
+					// TODO let cache in memory instead of disk.
+					element = cache.isEmpty() ? queues.spill.take() : cache.poll();
+				} catch (InterruptedException iex) {
+					if (isRunning()) {
+						LOG.error("Spilling thread was interrupted (without being shut down) while grabbing a buffer. " +
+								"Retrying to grab buffer...");
+						continue;
+					} else {
+						return;
+					}
+				}
+
+				// check if we are still running
+				if (!isRunning()) {
+					return;
+				}
+				// check if this is the end-of-work buffer
+				if (element == EOF_MARKER) {
+					break;
+				}
+
+				if (element.buffer.getOccupancy() > 0) {
+					// open next channel
+					FileIOChannel.ID channel = enumerator.next();
+					channelManager.addChannel(channel);
+
+					AbstractChannelWriterOutputView output = null;
+					int bytesInLastBuffer;
+					int blockCount;
+
+					try {
+						numSpillFiles++;
+						output = FileChannelUtil.createOutputView(ioManager, channel, compressionEnable,
+								compressionCodecFactory, compressionBlockSize, memorySegmentSize);
+						element.buffer.writeToOutput(output);
+						spillInBytes += output.getNumBytes();
+						spillInCompressedBytes += output.getNumCompressedBytes();
+						bytesInLastBuffer = output.close();
+						blockCount = output.getBlockCount();
+						LOG.info("here spill the {}th sort buffer data with {} bytes and {} compressed bytes",
+								numSpillFiles, spillInBytes, spillInCompressedBytes);
+					} catch (IOException e) {
+						if (output != null) {
+							output.close();
+							output.getChannel().deleteChannel();
+						}
+						throw e;
+					}
+
+					// pass spill file meta to merging thread
+					this.queues.merge.add(new ChannelWithMeta(channel, blockCount, bytesInLastBuffer));
+				}
+
+				// pass empty sort-buffer to reading thread
+				element.buffer.reset();
+				this.queues.empty.add(element);
+			}
+
+			// clear the sort buffers, as both sorting and spilling threads are done.
+			releaseSortMemory();
+
+			// signal merging thread to begin the final merge
+			this.queues.merge.add(FINAL_MERGE_MARKER);
+
+			// Spilling thread done.
+		}
+
+		private void releaseEmptyBuffers() {
+			while (!this.queues.empty.isEmpty()) {
+				try {
+					CircularElement element = this.queues.empty.take();
+					element.buffer.dispose();
+				} catch (InterruptedException iex) {
+					if (isRunning()) {
+						LOG.error("Spilling thread was interrupted (without being shut down) while collecting empty " +
+							"buffers to release them. Retrying to collect buffers...");
+					} else {
+						break;
+					}
+				}
+			}
+			releaseCoreSegments();
+		}
+	}
+
+	/**
+	 * The thread that merges the intermediate spill files and the merged files
+	 * until sufficiently few channels remain to perform the final streamed merge.
+	 */
+	private class MergingThread extends ThreadBase {
+
+		private final IOManager ioManager;                // I/O manager to create channels
+
+		private final int maxFanIn;
+
+		private final BinaryExternalMerger merger;
+
+		public MergingThread(
+				ExceptionHandler<IOException> exceptionHandler,
+				CircularQueues queues, IOManager ioManager,
+				int maxNumFileHandles, BinaryExternalMerger merger) {
+			super(exceptionHandler, "SortMerger merging thread", queues);
+			this.ioManager = ioManager;
+			this.maxFanIn = maxNumFileHandles;
+			this.merger = merger;
+		}
+
+		@Override
+		public void go() throws IOException {
+
+			final List<ChannelWithMeta> spillChannelIDs = new ArrayList<>();
+			List<ChannelWithMeta> finalMergeChannelIDs = new ArrayList<>();
+			ChannelWithMeta channelID;
+
+			while (isRunning()) {
+				try {
+					channelID = this.queues.merge.take();
+				} catch (InterruptedException iex) {
+					if (isRunning()) {
+						LOG.error("Merging thread was interrupted (without being shut down) " +
+							"while grabbing a channel with meta. Retrying...");
+						continue;
+					} else {
+						return;
+					}
+				}
+
+				if (!isRunning()) {
+					return;
+				}
+				if (channelID == FINAL_MERGE_MARKER) {
+					finalMergeChannelIDs.addAll(spillChannelIDs);
+					spillChannelIDs.clear();
+					// sort file channels by block numbers, to ensure a better merging performance
+					finalMergeChannelIDs.sort(Comparator.comparingInt(ChannelWithMeta::getBlockCount));
+					break;
+				}
+
+				spillChannelIDs.add(channelID);
+				// if async merge is disabled, we will only do the final merge
+				// otherwise we wait for `maxFanIn` number of channels to begin a merge
+				if (!asyncMergeEnable || spillChannelIDs.size() < maxFanIn) {
+					continue;
+				}
+
+				// perform a intermediate merge
+				finalMergeChannelIDs.addAll(merger.mergeChannelList(spillChannelIDs));
+				spillChannelIDs.clear();
+			}
+
+			// check if we have spilled some data at all
+			if (finalMergeChannelIDs.isEmpty()) {
+				if (iterator == null) {
+					// only set the iterator if it's not set
+					// by the in memory merge stage of spilling thread.
+					setResultIterator(EmptyMutableObjectIterator.get());
+				}
+			} else {
+				// merge channels until sufficient file handles are available
+				while (isRunning() && finalMergeChannelIDs.size() > this.maxFanIn) {
+					finalMergeChannelIDs = merger.mergeChannelList(finalMergeChannelIDs);
+				}
+
+				// Beginning final merge.
+
+				// no need to call `getReadMemoryFromHeap` again,
+				// because `finalMergeChannelIDs` must become smaller
+
+				List<FileIOChannel> openChannels = new ArrayList<>();
+				BinaryMergeIterator<BinaryRow> iterator = merger.getMergingIterator(
+					finalMergeChannelIDs, openChannels);
+				channelManager.addOpenChannels(openChannels);
+
+				setResultIterator(iterator);
+			}
+
+			// Merging thread done.
+		}
+	}
+
+	public long getUsedMemoryInBytes() {
+		long usedSizeInBytes = 0;
+		for (BinaryInMemorySortBuffer sortBuffer : sortBuffers) {
+			usedSizeInBytes += sortBuffer.getOccupancy();
+		}
+		return usedSizeInBytes;
+	}
+
+	public long getNumSpillFiles() {
+		return numSpillFiles;
+	}
+
+	public long getSpillInBytes() {
+		return spillInBytes;
+	}
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BinaryInMemorySortBuffer.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BinaryInMemorySortBuffer.java
new file mode 100644
index 0000000..166afca
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BinaryInMemorySortBuffer.java
@@ -0,0 +1,222 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.core.memory.MemorySegment;
+import org.apache.flink.runtime.io.disk.SimpleCollectingOutputView;
+import org.apache.flink.table.dataformat.BaseRow;
+import org.apache.flink.table.dataformat.BinaryRow;
+import org.apache.flink.table.runtime.util.MemorySegmentPool;
+import org.apache.flink.table.typeutils.AbstractRowSerializer;
+import org.apache.flink.table.typeutils.BinaryRowSerializer;
+import org.apache.flink.util.MutableObjectIterator;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkArgument;
+
+/**
+ * In memory sort buffer for binary row.
+ */
+public final class BinaryInMemorySortBuffer extends BinaryIndexedSortable {
+
+	private static final int MIN_REQUIRED_BUFFERS = 3;
+
+	private AbstractRowSerializer<BaseRow> inputSerializer;
+	private final ArrayList<MemorySegment> recordBufferSegments;
+	private final SimpleCollectingOutputView recordCollector;
+	private final int totalNumBuffers;
+
+	private long currentDataBufferOffset;
+	private long sortIndexBytes;
+
+	/**
+	 * Create a memory sorter in `insert` way.
+	 */
+	public static BinaryInMemorySortBuffer createBuffer(
+			NormalizedKeyComputer normalizedKeyComputer,
+			AbstractRowSerializer<BaseRow> inputSerializer,
+			BinaryRowSerializer serializer,
+			RecordComparator comparator,
+			List<MemorySegment> memory) throws IOException {
+		checkArgument(memory.size() >= MIN_REQUIRED_BUFFERS);
+		int totalNumBuffers = memory.size();
+		ListMemorySegmentPool pool = new ListMemorySegmentPool(memory);
+		ArrayList<MemorySegment> recordBufferSegments = new ArrayList<>(16);
+		return new BinaryInMemorySortBuffer(
+				normalizedKeyComputer, inputSerializer, serializer, comparator, recordBufferSegments,
+				new SimpleCollectingOutputView(recordBufferSegments, pool, pool.pageSize()),
+				pool, totalNumBuffers);
+	}
+
+	private BinaryInMemorySortBuffer(
+			NormalizedKeyComputer normalizedKeyComputer,
+			AbstractRowSerializer<BaseRow> inputSerializer,
+			BinaryRowSerializer serializer,
+			RecordComparator comparator,
+			ArrayList<MemorySegment> recordBufferSegments,
+			SimpleCollectingOutputView recordCollector,
+			MemorySegmentPool pool,
+			int totalNumBuffers) throws IOException {
+		super(normalizedKeyComputer, serializer, comparator, recordBufferSegments, pool);
+		this.inputSerializer = inputSerializer;
+		this.recordBufferSegments = recordBufferSegments;
+		this.recordCollector = recordCollector;
+		this.totalNumBuffers = totalNumBuffers;
+	}
+
+	// -------------------------------------------------------------------------
+	// Memory Segment
+	// -------------------------------------------------------------------------
+
+	/**
+	 * Resets the sort buffer back to the state where it is empty. All contained data is discarded.
+	 */
+	public void reset() {
+
+		// reset all offsets
+		this.numRecords = 0;
+		this.currentSortIndexOffset = 0;
+		this.currentDataBufferOffset = 0;
+		this.sortIndexBytes = 0;
+
+		// return all memory
+		returnToSegmentPool();
+
+		// grab first buffers
+		this.currentSortIndexSegment = nextMemorySegment();
+		this.sortIndex.add(this.currentSortIndexSegment);
+		this.recordCollector.reset();
+	}
+
+	public void returnToSegmentPool() {
+		// return all memory
+		this.memorySegmentPool.returnAll(this.sortIndex);
+		this.memorySegmentPool.returnAll(this.recordBufferSegments);
+		this.sortIndex.clear();
+		this.recordBufferSegments.clear();
+	}
+
+	/**
+	 * Checks whether the buffer is empty.
+	 *
+	 * @return True, if no record is contained, false otherwise.
+	 */
+	public boolean isEmpty() {
+		return this.numRecords == 0;
+	}
+
+	public void dispose() {
+		returnToSegmentPool();
+	}
+
+	public long getCapacity() {
+		return ((long) this.totalNumBuffers) * memorySegmentPool.pageSize();
+	}
+
+	public long getOccupancy() {
+		return this.currentDataBufferOffset + this.sortIndexBytes;
+	}
+
+	/**
+	 * Writes a given record to this sort buffer. The written record will be appended and take
+	 * the last logical position.
+	 *
+	 * @param record The record to be written.
+	 * @return True, if the record was successfully written, false, if the sort buffer was full.
+	 * @throws IOException Thrown, if an error occurred while serializing the record into the buffers.
+	 */
+	public boolean write(BaseRow record) throws IOException {
+		//check whether we need a new memory segment for the sort index
+		if (!checkNextIndexOffset()) {
+			return false;
+		}
+
+		// serialize the record into the data buffers
+		int skip;
+		try {
+			skip = this.inputSerializer.serializeToPages(record, this.recordCollector);
+		} catch (EOFException e) {
+			return false;
+		}
+
+		final long newOffset = this.recordCollector.getCurrentOffset();
+		long currOffset = currentDataBufferOffset + skip;
+
+		writeIndexAndNormalizedKey(record, currOffset);
+
+		this.currentDataBufferOffset = newOffset;
+
+		return true;
+	}
+
+	private BinaryRow getRecordFromBuffer(BinaryRow reuse, long pointer) throws IOException {
+		this.recordBuffer.setReadPosition(pointer);
+		return this.serializer.mapFromPages(reuse, this.recordBuffer);
+	}
+
+	// -------------------------------------------------------------------------
+
+	/**
+	 * Gets an iterator over all records in this buffer in their logical order.
+	 *
+	 * @return An iterator returning the records in their logical order.
+	 */
+	public final MutableObjectIterator<BinaryRow> getIterator() {
+		return new MutableObjectIterator<BinaryRow>() {
+			private final int size = size();
+			private int current = 0;
+
+			private int currentSegment = 0;
+			private int currentOffset = 0;
+
+			private MemorySegment currentIndexSegment = sortIndex.get(0);
+
+			@Override
+			public BinaryRow next(BinaryRow target) {
+				if (this.current < this.size) {
+					this.current++;
+					if (this.currentOffset > lastIndexEntryOffset) {
+						this.currentOffset = 0;
+						this.currentIndexSegment = sortIndex.get(++this.currentSegment);
+					}
+
+					long pointer = this.currentIndexSegment.getLong(this.currentOffset);
+					this.currentOffset += indexEntrySize;
+
+					try {
+						return getRecordFromBuffer(target, pointer);
+					} catch (IOException ioe) {
+						throw new RuntimeException(ioe);
+					}
+				} else {
+					return null;
+				}
+			}
+
+			@Override
+			public BinaryRow next() {
+				throw new RuntimeException("Not support!");
+			}
+		};
+	}
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BinaryIndexedSortable.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BinaryIndexedSortable.java
new file mode 100644
index 0000000..a4606c1
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BinaryIndexedSortable.java
@@ -0,0 +1,250 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.core.memory.MemorySegment;
+import org.apache.flink.runtime.io.disk.RandomAccessInputView;
+import org.apache.flink.runtime.memory.AbstractPagedOutputView;
+import org.apache.flink.runtime.operators.sort.IndexedSortable;
+import org.apache.flink.table.dataformat.BaseRow;
+import org.apache.flink.table.dataformat.BinaryRow;
+import org.apache.flink.table.runtime.util.MemorySegmentPool;
+import org.apache.flink.table.typeutils.BinaryRowSerializer;
+
+import java.io.IOException;
+import java.util.ArrayList;
+
+/**
+ * abstract sortable, provide basic compare and swap. Support writing of index and normalizedKey.
+ */
+public abstract class BinaryIndexedSortable implements IndexedSortable {
+
+	public static final int OFFSET_LEN = 8;
+
+	// put/compare/swap normalized key
+	private final NormalizedKeyComputer normalizedKeyComputer;
+	protected final BinaryRowSerializer serializer;
+
+	// if normalized key not fully determines, need compare record.
+	private final RecordComparator comparator;
+
+	protected final RandomAccessInputView recordBuffer;
+	private final RandomAccessInputView recordBufferForComparison;
+
+	// segments
+	protected MemorySegment currentSortIndexSegment;
+	protected final MemorySegmentPool memorySegmentPool;
+	protected final ArrayList<MemorySegment> sortIndex;
+
+	// normalized key attributes
+	private final int numKeyBytes;
+	protected final int indexEntrySize;
+	private final int indexEntriesPerSegment;
+	protected final int lastIndexEntryOffset;
+	private final boolean normalizedKeyFullyDetermines;
+	private final boolean useNormKeyUninverted;
+
+	// for serialized comparison
+	protected final BinaryRowSerializer serializer1;
+	private final BinaryRowSerializer serializer2;
+	protected final BinaryRow row1;
+	private final BinaryRow row2;
+
+	// runtime variables
+	protected int currentSortIndexOffset;
+	protected int numRecords;
+
+	public BinaryIndexedSortable(
+			NormalizedKeyComputer normalizedKeyComputer,
+			BinaryRowSerializer serializer,
+			RecordComparator comparator,
+			ArrayList<MemorySegment> recordBufferSegments,
+			MemorySegmentPool memorySegmentPool) throws IOException {
+		if (normalizedKeyComputer == null || serializer == null) {
+			throw new NullPointerException();
+		}
+		this.normalizedKeyComputer = normalizedKeyComputer;
+		this.serializer = serializer;
+		this.comparator = comparator;
+		this.memorySegmentPool = memorySegmentPool;
+		this.useNormKeyUninverted = !normalizedKeyComputer.invertKey();
+
+		this.numKeyBytes = normalizedKeyComputer.getNumKeyBytes();
+
+		int segmentSize = memorySegmentPool.pageSize();
+		this.recordBuffer = new RandomAccessInputView(recordBufferSegments, segmentSize);
+		this.recordBufferForComparison = new RandomAccessInputView(recordBufferSegments, segmentSize);
+
+		this.normalizedKeyFullyDetermines = normalizedKeyComputer.isKeyFullyDetermines();
+
+		// compute the index entry size and limits
+		this.indexEntrySize = numKeyBytes + OFFSET_LEN;
+		this.indexEntriesPerSegment = segmentSize / this.indexEntrySize;
+		this.lastIndexEntryOffset = (this.indexEntriesPerSegment - 1) * this.indexEntrySize;
+
+		this.serializer1 = (BinaryRowSerializer) serializer.duplicate();
+		this.serializer2 = (BinaryRowSerializer) serializer.duplicate();
+		this.row1 = this.serializer1.createInstance();
+		this.row2 = this.serializer2.createInstance();
+
+		// set to initial state
+		this.sortIndex = new ArrayList<>(16);
+		this.currentSortIndexSegment = nextMemorySegment();
+		sortIndex.add(currentSortIndexSegment);
+	}
+
+	protected MemorySegment nextMemorySegment() {
+		return this.memorySegmentPool.nextSegment();
+	}
+
+	/**
+	 * check if we need request next index memory.
+	 */
+	protected boolean checkNextIndexOffset() {
+		if (this.currentSortIndexOffset > this.lastIndexEntryOffset) {
+			MemorySegment returnSegment = nextMemorySegment();
+			if (returnSegment != null) {
+				this.currentSortIndexSegment = returnSegment;
+				this.sortIndex.add(this.currentSortIndexSegment);
+				this.currentSortIndexOffset = 0;
+			} else {
+				return false;
+			}
+		}
+		return true;
+	}
+
+	/**
+	 * Write of index and normalizedKey.
+	 */
+	protected void writeIndexAndNormalizedKey(BaseRow record, long currOffset) {
+		// add the pointer and the normalized key
+		this.currentSortIndexSegment.putLong(this.currentSortIndexOffset, currOffset);
+
+		if (this.numKeyBytes != 0) {
+			normalizedKeyComputer.putKey(record, this.currentSortIndexSegment, this.currentSortIndexOffset + OFFSET_LEN);
+		}
+
+		this.currentSortIndexOffset += this.indexEntrySize;
+		this.numRecords++;
+	}
+
+	@Override
+	public int compare(int i, int j) {
+		final int segmentNumberI = i / this.indexEntriesPerSegment;
+		final int segmentOffsetI = (i % this.indexEntriesPerSegment) * this.indexEntrySize;
+
+		final int segmentNumberJ = j / this.indexEntriesPerSegment;
+		final int segmentOffsetJ = (j % this.indexEntriesPerSegment) * this.indexEntrySize;
+
+		return compare(segmentNumberI, segmentOffsetI, segmentNumberJ, segmentOffsetJ);
+	}
+
+	@Override
+	public int compare(int segmentNumberI, int segmentOffsetI, int segmentNumberJ, int segmentOffsetJ) {
+		final MemorySegment segI = this.sortIndex.get(segmentNumberI);
+		final MemorySegment segJ = this.sortIndex.get(segmentNumberJ);
+
+		int val = normalizedKeyComputer.compareKey(
+				segI, segmentOffsetI + OFFSET_LEN, segJ, segmentOffsetJ + OFFSET_LEN);
+
+		if (val != 0 || this.normalizedKeyFullyDetermines) {
+			return this.useNormKeyUninverted ? val : -val;
+		}
+
+		final long pointerI = segI.getLong(segmentOffsetI);
+		final long pointerJ = segJ.getLong(segmentOffsetJ);
+
+		return compareRecords(pointerI, pointerJ);
+	}
+
+	private int compareRecords(long pointer1, long pointer2) {
+		this.recordBuffer.setReadPosition(pointer1);
+		this.recordBufferForComparison.setReadPosition(pointer2);
+
+		try {
+			return this.comparator.compare(
+					serializer1.mapFromPages(row1, recordBuffer),
+					serializer2.mapFromPages(row2, recordBufferForComparison));
+		} catch (IOException ioex) {
+			throw new RuntimeException("Error comparing two records.", ioex);
+		}
+	}
+
+	@Override
+	public void swap(int i, int j) {
+		final int segmentNumberI = i / this.indexEntriesPerSegment;
+		final int segmentOffsetI = (i % this.indexEntriesPerSegment) * this.indexEntrySize;
+
+		final int segmentNumberJ = j / this.indexEntriesPerSegment;
+		final int segmentOffsetJ = (j % this.indexEntriesPerSegment) * this.indexEntrySize;
+
+		swap(segmentNumberI, segmentOffsetI, segmentNumberJ, segmentOffsetJ);
+	}
+
+	@Override
+	public void swap(int segmentNumberI, int segmentOffsetI, int segmentNumberJ, int segmentOffsetJ) {
+		final MemorySegment segI = this.sortIndex.get(segmentNumberI);
+		final MemorySegment segJ = this.sortIndex.get(segmentNumberJ);
+
+		// swap offset
+		long index = segI.getLong(segmentOffsetI);
+		segI.putLong(segmentOffsetI, segJ.getLong(segmentOffsetJ));
+		segJ.putLong(segmentOffsetJ, index);
+
+		// swap key
+		normalizedKeyComputer.swapKey(segI, segmentOffsetI + OFFSET_LEN, segJ, segmentOffsetJ + OFFSET_LEN);
+	}
+
+	@Override
+	public int size() {
+		return this.numRecords;
+	}
+
+	@Override
+	public int recordSize() {
+		return indexEntrySize;
+	}
+
+	@Override
+	public int recordsPerSegment() {
+		return indexEntriesPerSegment;
+	}
+
+	/**
+	 * Spill: Write all records to a {@link AbstractPagedOutputView}.
+	 */
+	public void writeToOutput(AbstractPagedOutputView output) throws IOException {
+		final int numRecords = this.numRecords;
+		int currentMemSeg = 0;
+		int currentRecord = 0;
+
+		while (currentRecord < numRecords) {
+			final MemorySegment currentIndexSegment = this.sortIndex.get(currentMemSeg++);
+
+			// go through all records in the memory segment
+			for (int offset = 0; currentRecord < numRecords && offset <= this.lastIndexEntryOffset; currentRecord++, offset += this.indexEntrySize) {
+				final long pointer = currentIndexSegment.getLong(offset);
+
+				this.recordBuffer.setReadPosition(pointer);
+				this.serializer.copyFromPagesToView(this.recordBuffer, output);
+			}
+		}
+	}
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BinaryKVExternalMerger.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BinaryKVExternalMerger.java
new file mode 100644
index 0000000..487651c
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BinaryKVExternalMerger.java
@@ -0,0 +1,94 @@
+/*
+* Licensed to the Apache Software Foundation (ASF) under one or more
+* contributor license agreements.	See the NOTICE file distributed with
+* this work for additional information regarding copyright ownership.
+* The ASF licenses this file to You under the Apache License, Version 2.0
+* (the "License"); you may not use this file except in compliance with
+* the License.	You may obtain a copy of the License at
+*
+*		http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.runtime.io.disk.iomanager.AbstractChannelReaderInputView;
+import org.apache.flink.runtime.io.disk.iomanager.IOManager;
+import org.apache.flink.runtime.memory.AbstractPagedOutputView;
+import org.apache.flink.table.dataformat.BinaryRow;
+import org.apache.flink.table.runtime.compression.BlockCompressionFactory;
+import org.apache.flink.table.typeutils.BinaryRowSerializer;
+import org.apache.flink.util.MutableObjectIterator;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+
+/**
+ * Key-Value style record merger for sort.
+ */
+public class BinaryKVExternalMerger extends AbstractBinaryExternalMerger<Tuple2<BinaryRow, BinaryRow>> {
+
+	private final BinaryRowSerializer keySerializer;
+	private final BinaryRowSerializer valueSerializer;
+	private final RecordComparator comparator;
+
+	public BinaryKVExternalMerger(
+			IOManager ioManager,
+			int pageSize,
+			int maxFanIn,
+			SpillChannelManager channelManager,
+			BinaryRowSerializer keySerializer,
+			BinaryRowSerializer valueSerializer,
+			RecordComparator comparator,
+			boolean compressionEnable,
+			BlockCompressionFactory compressionCodecFactory,
+			int compressionBlockSize) {
+		super(ioManager, pageSize, maxFanIn, channelManager, compressionEnable, compressionCodecFactory, compressionBlockSize);
+		this.keySerializer = keySerializer;
+		this.valueSerializer = valueSerializer;
+		this.comparator = comparator;
+	}
+
+	@Override
+	protected List<Tuple2<BinaryRow, BinaryRow>> mergeReusedEntries(int size) {
+		ArrayList<Tuple2<BinaryRow, BinaryRow>> reused = new ArrayList<>(size);
+		for (int i = 0; i < size; i++) {
+			reused.add(
+					new Tuple2<>(keySerializer.createInstance(), valueSerializer.createInstance()));
+		}
+		return reused;
+	}
+
+	@Override
+	protected MutableObjectIterator<Tuple2<BinaryRow, BinaryRow>> channelReaderInputViewIterator(
+			AbstractChannelReaderInputView inView) {
+		return new ChannelReaderKVInputViewIterator<>(
+				inView, null, keySerializer.duplicate(), valueSerializer.duplicate());
+	}
+
+	@Override
+	protected Comparator<Tuple2<BinaryRow, BinaryRow>> mergeComparator() {
+		return (o1, o2) -> comparator.compare(o1.f0, o2.f0);
+	}
+
+	@Override
+	protected void writeMergingOutput(
+			MutableObjectIterator<Tuple2<BinaryRow, BinaryRow>> mergeIterator,
+			AbstractPagedOutputView output) throws IOException {
+		// read the merged stream and write the data back
+		Tuple2<BinaryRow, BinaryRow> kv = new Tuple2<>(
+				keySerializer.createInstance(), valueSerializer.createInstance());
+		while ((kv = mergeIterator.next(kv)) != null) {
+			keySerializer.serialize(kv.f0, output);
+			valueSerializer.serialize(kv.f1, output);
+		}
+	}
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BinaryKVInMemorySortBuffer.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BinaryKVInMemorySortBuffer.java
new file mode 100644
index 0000000..642d81b
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BinaryKVInMemorySortBuffer.java
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.	See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.	You may obtain a copy of the License at
+ *
+ *		http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.core.memory.MemorySegment;
+import org.apache.flink.runtime.io.disk.RandomAccessInputView;
+import org.apache.flink.runtime.memory.AbstractPagedOutputView;
+import org.apache.flink.table.dataformat.BinaryRow;
+import org.apache.flink.table.runtime.util.MemorySegmentPool;
+import org.apache.flink.table.typeutils.BinaryRowSerializer;
+
+import java.io.IOException;
+import java.util.ArrayList;
+
+import static org.apache.flink.util.Preconditions.checkArgument;
+
+/**
+ * In memory KV sortable buffer for binary row, it already has records in memory.
+ */
+public class BinaryKVInMemorySortBuffer extends BinaryIndexedSortable {
+
+	private final BinaryRowSerializer valueSerializer;
+
+	public static BinaryKVInMemorySortBuffer createBuffer(
+			NormalizedKeyComputer normalizedKeyComputer,
+			BinaryRowSerializer keySerializer,
+			BinaryRowSerializer valueSerializer,
+			RecordComparator comparator,
+			ArrayList<MemorySegment> recordBufferSegments,
+			long numElements,
+			MemorySegmentPool pool) throws IOException {
+		BinaryKVInMemorySortBuffer sorter = new BinaryKVInMemorySortBuffer(
+				normalizedKeyComputer, keySerializer, valueSerializer, comparator,
+				recordBufferSegments, pool);
+		sorter.load(numElements, sorter.recordBuffer);
+		return sorter;
+	}
+
+	private BinaryKVInMemorySortBuffer(
+			NormalizedKeyComputer normalizedKeyComputer,
+			BinaryRowSerializer keySerializer,
+			BinaryRowSerializer valueSerializer,
+			RecordComparator comparator,
+			ArrayList<MemorySegment> recordBufferSegments,
+			MemorySegmentPool memorySegmentPool) throws IOException {
+		super(normalizedKeyComputer, keySerializer, comparator, recordBufferSegments, memorySegmentPool);
+		this.valueSerializer = valueSerializer;
+	}
+
+	@Override
+	public void writeToOutput(AbstractPagedOutputView output) throws IOException {
+		final int numRecords = this.numRecords;
+		int currentMemSeg = 0;
+		int currentRecord = 0;
+
+		while (currentRecord < numRecords) {
+			final MemorySegment currentIndexSegment = this.sortIndex.get(currentMemSeg++);
+
+			// go through all records in the memory segment
+			for (int offset = 0; currentRecord < numRecords && offset <= this.lastIndexEntryOffset; currentRecord++,
+					offset += this.indexEntrySize) {
+				final long pointer = currentIndexSegment.getLong(offset);
+				this.recordBuffer.setReadPosition(pointer);
+				this.serializer.copyFromPagesToView(this.recordBuffer, output);
+				this.valueSerializer.copyFromPagesToView(this.recordBuffer, output);
+			}
+		}
+	}
+
+	private void load(long numElements,
+			RandomAccessInputView recordInputView) throws IOException {
+		for (int index = 0; index < numElements; index++) {
+			serializer.checkSkipReadForFixLengthPart(recordInputView);
+			long pointer = recordInputView.getReadPosition();
+			BinaryRow row = serializer1.mapFromPages(row1, recordInputView);
+			valueSerializer.checkSkipReadForFixLengthPart(recordInputView);
+			recordInputView.skipBytes(recordInputView.readInt());
+			boolean success = checkNextIndexOffset();
+			checkArgument(success);
+			writeIndexAndNormalizedKey(row, pointer);
+		}
+	}
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BinaryMergeIterator.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BinaryMergeIterator.java
new file mode 100644
index 0000000..fe3e1c0
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BinaryMergeIterator.java
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.runtime.operators.sort.MergeIterator;
+import org.apache.flink.runtime.operators.sort.PartialOrderPriorityQueue;
+import org.apache.flink.util.MutableObjectIterator;
+
+import java.io.IOException;
+import java.util.Comparator;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkArgument;
+
+/**
+ * Binary version of {@link MergeIterator}.
+ * Use {@link RecordComparator} to compare record.
+ */
+public class BinaryMergeIterator<Entry> implements MutableObjectIterator<Entry> {
+
+	// heap over the head elements of the stream
+	private final PartialOrderPriorityQueue<HeadStream<Entry>> heap;
+	private HeadStream<Entry> currHead;
+
+	public BinaryMergeIterator(
+			List<MutableObjectIterator<Entry>> iterators,
+			List<Entry> reusableEntries,
+			Comparator<Entry> comparator) throws IOException {
+		checkArgument(iterators.size() == reusableEntries.size());
+		this.heap = new PartialOrderPriorityQueue<>(
+				(o1, o2) -> comparator.compare(o1.getHead(), o2.getHead()), iterators.size());
+		for (int i = 0; i < iterators.size(); i++) {
+			this.heap.add(new HeadStream<>(iterators.get(i), reusableEntries.get(i)));
+		}
+	}
+
+	@Override
+	public Entry next(Entry reuse) throws IOException {
+		// Ignore reuse, because each HeadStream has its own reuse BinaryRow.
+		return next();
+	}
+
+	@Override
+	public Entry next() throws IOException {
+		if (currHead != null) {
+			if (!currHead.nextHead()) {
+				this.heap.poll();
+			} else {
+				this.heap.adjustTop();
+			}
+		}
+
+		if (this.heap.size() > 0) {
+			currHead = this.heap.peek();
+			return currHead.getHead();
+		} else {
+			return null;
+		}
+	}
+
+	private static final class HeadStream<Entry> {
+
+		private final MutableObjectIterator<Entry> iterator;
+		private Entry head;
+
+		private HeadStream(MutableObjectIterator<Entry> iterator, Entry head) throws IOException {
+			this.iterator = iterator;
+			this.head = head;
+			if (!nextHead()) {
+				throw new IllegalStateException();
+			}
+		}
+
+		private Entry getHead() {
+			return this.head;
+		}
+
+		private boolean nextHead() throws IOException {
+			return (this.head = this.iterator.next(head)) != null;
+		}
+	}
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BufferedKVExternalSorter.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BufferedKVExternalSorter.java
new file mode 100644
index 0000000..3c23738
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/BufferedKVExternalSorter.java
@@ -0,0 +1,184 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.	See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.	You may obtain a copy of the License at
+ *
+ *		http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.core.memory.MemorySegment;
+import org.apache.flink.runtime.io.disk.iomanager.AbstractChannelWriterOutputView;
+import org.apache.flink.runtime.io.disk.iomanager.FileIOChannel;
+import org.apache.flink.runtime.io.disk.iomanager.IOManager;
+import org.apache.flink.runtime.operators.sort.IndexedSorter;
+import org.apache.flink.runtime.operators.sort.QuickSort;
+import org.apache.flink.table.api.TableConfigOptions;
+import org.apache.flink.table.dataformat.BinaryRow;
+import org.apache.flink.table.runtime.compression.BlockCompressionFactory;
+import org.apache.flink.table.runtime.io.ChannelWithMeta;
+import org.apache.flink.table.runtime.util.FileChannelUtil;
+import org.apache.flink.table.runtime.util.MemorySegmentPool;
+import org.apache.flink.table.typeutils.BinaryRowSerializer;
+import org.apache.flink.util.MutableObjectIterator;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Sorter for buffered input in the form of Key-Value Style.
+ * First, sort and spill buffered inputs (without data copy, just write index and normalized key).
+ * Second, merge disk outputs and return iterator.
+ *
+ * <p>For Hash Aggregation:We store the data in MemorySegmentHashTable in KeyValue format.
+ * When memory is not enough, we spill all the data in memory onto disk and degenerate it into
+ * Sort Aggregation. So we need a BufferedKVExternalSorter to write the data that already in
+ * memory to disk, and then carry out SortMerge.
+ */
+public class BufferedKVExternalSorter {
+
+	private static final Logger LOG = LoggerFactory.getLogger(BufferedKVExternalSorter.class);
+
+	private volatile boolean closed = false;
+
+	private final NormalizedKeyComputer nKeyComputer;
+	private final RecordComparator comparator;
+	private final BinaryRowSerializer keySerializer;
+	private final BinaryRowSerializer valueSerializer;
+	private final IndexedSorter sorter;
+
+	private final BinaryKVExternalMerger merger;
+
+	private final IOManager ioManager;
+	private final int maxNumFileHandles;
+	private final FileIOChannel.Enumerator enumerator;
+	private final List<ChannelWithMeta> channelIDs = new ArrayList<>();
+	private final SpillChannelManager channelManager;
+
+	private int pageSize;
+
+	//metric
+	private long numSpillFiles;
+	private long spillInBytes;
+	private long spillInCompressedBytes;
+
+	private final boolean compressionEnable;
+	private final BlockCompressionFactory compressionCodecFactory;
+	private final int compressionBlockSize;
+
+	public BufferedKVExternalSorter(
+			IOManager ioManager,
+			BinaryRowSerializer keySerializer,
+			BinaryRowSerializer valueSerializer,
+			NormalizedKeyComputer nKeyComputer,
+			RecordComparator comparator,
+			int pageSize,
+			Configuration conf) throws IOException {
+		this.keySerializer = keySerializer;
+		this.valueSerializer = valueSerializer;
+		this.nKeyComputer = nKeyComputer;
+		this.comparator = comparator;
+		this.pageSize = pageSize;
+		this.sorter = new QuickSort();
+		this.maxNumFileHandles = conf.getInteger(TableConfigOptions.SQL_EXEC_SORT_FILE_HANDLES_MAX_NUM);
+		this.compressionEnable = conf.getBoolean(TableConfigOptions.SQL_EXEC_SPILL_COMPRESSION_ENABLED);
+		this.compressionCodecFactory = this.compressionEnable
+			? BlockCompressionFactory.createBlockCompressionFactory(
+					conf.getString(TableConfigOptions.SQL_EXEC_SPILL_COMPRESSION_CODEC))
+			: null;
+		this.compressionBlockSize = conf.getInteger(TableConfigOptions.SQL_EXEC_SPILL_COMPRESSION_BLOCK_SIZE);
+		this.ioManager = ioManager;
+		this.enumerator = this.ioManager.createChannelEnumerator();
+		this.channelManager = new SpillChannelManager();
+		this.merger = new BinaryKVExternalMerger(
+				ioManager, pageSize,
+				maxNumFileHandles, channelManager,
+				keySerializer, valueSerializer, comparator,
+				compressionEnable,
+			compressionCodecFactory,
+				compressionBlockSize);
+	}
+
+	public MutableObjectIterator<Tuple2<BinaryRow, BinaryRow>> getKVIterator() throws IOException {
+		// 1. merge if more than maxNumFile
+		// merge channels until sufficient file handles are available
+		List<ChannelWithMeta> channelIDs = this.channelIDs;
+		while (!closed && channelIDs.size() > this.maxNumFileHandles) {
+			channelIDs = merger.mergeChannelList(channelIDs);
+		}
+
+		// 2. final merge
+		List<FileIOChannel> openChannels = new ArrayList<>();
+		BinaryMergeIterator<Tuple2<BinaryRow, BinaryRow>> iterator =
+				merger.getMergingIterator(channelIDs, openChannels);
+		channelManager.addOpenChannels(openChannels);
+
+		return iterator;
+	}
+
+	public void sortAndSpill(
+			ArrayList<MemorySegment> recordBufferSegments,
+			long numElements,
+			MemorySegmentPool pool) throws IOException {
+
+		// 1. sort buffer
+		BinaryKVInMemorySortBuffer buffer =
+				BinaryKVInMemorySortBuffer.createBuffer(
+						nKeyComputer, keySerializer, valueSerializer, comparator,
+						recordBufferSegments, numElements, pool);
+		this.sorter.sort(buffer);
+
+		// 2. spill
+		FileIOChannel.ID channel = enumerator.next();
+		channelManager.addChannel(channel);
+
+		AbstractChannelWriterOutputView output = null;
+		int bytesInLastBuffer;
+		int blockCount;
+		try {
+			numSpillFiles++;
+			output = FileChannelUtil.createOutputView(ioManager, channel, compressionEnable,
+					compressionCodecFactory, compressionBlockSize, pageSize);
+			buffer.writeToOutput(output);
+			spillInBytes += output.getNumBytes();
+			spillInCompressedBytes += output.getNumCompressedBytes();
+			bytesInLastBuffer = output.close();
+			blockCount = output.getBlockCount();
+			LOG.info("here spill the {}th kv external buffer data with {} bytes and {} compressed bytes",
+					numSpillFiles, spillInBytes, spillInCompressedBytes);
+		} catch (IOException e) {
+			if (output != null) {
+				output.close();
+				output.getChannel().deleteChannel();
+			}
+			throw e;
+		}
+		channelIDs.add(new ChannelWithMeta(channel, blockCount, bytesInLastBuffer));
+	}
+
+	public void close() {
+		if (closed) {
+			return;
+		}
+		// mark as closed
+		closed = true;
+		merger.close();
+		channelManager.close();
+	}
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/ChannelReaderKVInputViewIterator.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/ChannelReaderKVInputViewIterator.java
new file mode 100644
index 0000000..4b05756
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/ChannelReaderKVInputViewIterator.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.api.common.typeutils.TypeSerializer;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.core.memory.MemorySegment;
+import org.apache.flink.runtime.io.disk.iomanager.AbstractChannelReaderInputView;
+import org.apache.flink.util.MutableObjectIterator;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.util.List;
+
+/**
+ * Key-Value style channel reader input view iterator.
+ */
+public class ChannelReaderKVInputViewIterator<K, V> implements MutableObjectIterator<Tuple2<K, V>> {
+	private final AbstractChannelReaderInputView inView;
+	private final TypeSerializer<K> keySerializer;
+	private final TypeSerializer<V> valueSerializer;
+	private final List<MemorySegment> freeMemTarget;
+
+	public ChannelReaderKVInputViewIterator(
+			AbstractChannelReaderInputView inView,
+			List<MemorySegment> freeMemTarget,
+			TypeSerializer<K> keySerializer,
+			TypeSerializer<V> valueSerializer) {
+		this.inView = inView;
+		this.freeMemTarget = freeMemTarget;
+		this.keySerializer = keySerializer;
+		this.valueSerializer = valueSerializer;
+	}
+
+	@Override
+	public Tuple2<K, V> next(Tuple2<K, V> kvPair) throws IOException {
+		try {
+			kvPair.f0 = this.keySerializer.deserialize(kvPair.f0, this.inView);
+			kvPair.f1 = this.valueSerializer.deserialize(kvPair.f1, this.inView);
+			return kvPair;
+		} catch (EOFException var4) {
+			List<MemorySegment> freeMem = this.inView.close();
+			if (this.freeMemTarget != null) {
+				this.freeMemTarget.addAll(freeMem);
+			}
+			return null;
+		}
+	}
+
+	@Override
+	public Tuple2<K, V> next() throws IOException {
+		throw new UnsupportedOperationException("not supported.");
+	}
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/ListMemorySegmentPool.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/ListMemorySegmentPool.java
new file mode 100644
index 0000000..3523997
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/ListMemorySegmentPool.java
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.core.memory.MemorySegment;
+import org.apache.flink.table.runtime.util.MemorySegmentPool;
+
+import java.util.List;
+
+/**
+ * MemorySegment pool of a MemorySegment list.
+ */
+public class ListMemorySegmentPool implements MemorySegmentPool {
+
+	private final List<MemorySegment> segments;
+	private final int pageSize;
+
+	public ListMemorySegmentPool(List<MemorySegment> memorySegments) {
+		this.segments = memorySegments;
+		this.pageSize = segments.get(0).size();
+	}
+
+	@Override
+	public MemorySegment nextSegment() {
+		if (this.segments.size() > 0) {
+			return this.segments.remove(this.segments.size() - 1);
+		} else {
+			return null;
+		}
+	}
+
+	@Override
+	public int pageSize() {
+		return pageSize;
+	}
+
+	@Override
+	public void returnAll(List<MemorySegment> memory) {
+		segments.addAll(memory);
+	}
+
+	@Override
+	public void clear() {
+		segments.clear();
+	}
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/NormalizedKeyComputer.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/NormalizedKeyComputer.java
new file mode 100644
index 0000000..121fb50
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/NormalizedKeyComputer.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.api.common.typeutils.TypeComparator;
+import org.apache.flink.api.common.typeutils.TypeSerializer;
+import org.apache.flink.core.memory.MemorySegment;
+import org.apache.flink.table.dataformat.BaseRow;
+
+/**
+ * Normalized key computer for {@link BinaryInMemorySortBuffer}.
+ * For performance, subclasses are usually implemented through CodeGenerator.
+ */
+public abstract class NormalizedKeyComputer {
+
+	protected TypeSerializer[] serializers;
+	protected TypeComparator[] comparators;
+
+	public void init(TypeSerializer[] serializers, TypeComparator[] comparators) {
+		this.serializers = serializers;
+		this.comparators = comparators;
+	}
+
+	/**
+	 * Writes a normalized key for the given record into the target {@link MemorySegment}.
+	 */
+	public abstract void putKey(BaseRow record, MemorySegment target, int offset);
+
+	/**
+	 * Compares two normalized keys in respective {@link MemorySegment}.
+	 */
+	public abstract int compareKey(MemorySegment segI, int offsetI, MemorySegment segJ, int offsetJ);
+
+	/**
+	 * Swaps two normalized keys in respective {@link MemorySegment}.
+	 */
+	public abstract void swapKey(MemorySegment segI, int offsetI, MemorySegment segJ, int offsetJ);
+
+	/**
+	 * Get normalized keys bytes length.
+	 */
+	public abstract int getNumKeyBytes();
+
+	/**
+	 * whether the normalized key can fully determines the comparison.
+	 */
+	public abstract boolean isKeyFullyDetermines();
+
+	/**
+	 * Flag whether normalized key comparisons should be inverted key.
+	 */
+	public abstract boolean invertKey();
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/RecordComparator.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/RecordComparator.java
new file mode 100644
index 0000000..c5a274e
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/RecordComparator.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.api.common.typeutils.TypeComparator;
+import org.apache.flink.api.common.typeutils.TypeSerializer;
+import org.apache.flink.table.dataformat.BaseRow;
+
+import java.io.Serializable;
+import java.util.Comparator;
+
+/**
+ * Record comparator for {@link BinaryInMemorySortBuffer}.
+ * For performance, subclasses are usually implemented through CodeGenerator.
+ */
+public abstract class RecordComparator implements Comparator<BaseRow>, Serializable {
+
+	private static final long serialVersionUID = 1L;
+
+	protected TypeSerializer[] serializers;
+	protected TypeComparator[] comparators;
+
+	public void init(TypeSerializer[] serializers, TypeComparator[] comparators) {
+		this.serializers = serializers;
+		this.comparators = comparators;
+	}
+
+	@Override
+	public abstract int compare(BaseRow o1, BaseRow o2);
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/SortUtil.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/SortUtil.java
new file mode 100644
index 0000000..a8e5607
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/SortUtil.java
@@ -0,0 +1,120 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.api.common.typeutils.base.NormalizedKeyUtil;
+import org.apache.flink.core.memory.MemorySegment;
+import org.apache.flink.table.dataformat.BinaryString;
+import org.apache.flink.table.dataformat.Decimal;
+
+/**
+ * Util for data formats.
+ */
+public class SortUtil {
+
+	public static void minNormalizedKey(MemorySegment target, int offset, int numBytes) {
+		//write min value.
+		for (int i = 0; i < numBytes; i++) {
+			target.put(offset + i, (byte) 0);
+		}
+	}
+
+	/**
+	 * Max unsigned byte is -1.
+	 */
+	public static void maxNormalizedKey(MemorySegment target, int offset, int numBytes) {
+		//write max value.
+		for (int i = 0; i < numBytes; i++) {
+			target.put(offset + i, (byte) -1);
+		}
+	}
+
+	public static void putShortNormalizedKey(short value, MemorySegment target, int offset,
+			int numBytes) {
+		NormalizedKeyUtil.putShortNormalizedKey(value, target, offset, numBytes);
+	}
+
+	public static void putByteNormalizedKey(byte value, MemorySegment target, int offset,
+			int numBytes) {
+		NormalizedKeyUtil.putByteNormalizedKey(value, target, offset, numBytes);
+	}
+
+	public static void putBooleanNormalizedKey(boolean value, MemorySegment target, int offset,
+			int numBytes) {
+		NormalizedKeyUtil.putBooleanNormalizedKey(value, target, offset, numBytes);
+	}
+
+	/**
+	 * UTF-8 supports bytes comparison.
+	 */
+	public static void putBinaryStringNormalizedKey(
+			BinaryString value, MemorySegment target, int offset, int numBytes) {
+		final int limit = offset + numBytes;
+		final int end = value.getSizeInBytes();
+		for (int i = 0; i < end && offset < limit; i++) {
+			target.put(offset++, value.getByte(i));
+		}
+
+		for (int i = offset; i < limit; i++) {
+			target.put(i, (byte) 0);
+		}
+	}
+
+	/**
+	 * Just support the compact precision decimal.
+	 */
+	public static void putDecimalNormalizedKey(
+			Decimal record, MemorySegment target, int offset, int len) {
+		assert record.getPrecision() <= Decimal.MAX_COMPACT_PRECISION;
+		putLongNormalizedKey(record.toUnscaledLong(), target, offset, len);
+	}
+
+	public static void putIntNormalizedKey(int value, MemorySegment target, int offset, int numBytes) {
+		NormalizedKeyUtil.putIntNormalizedKey(value, target, offset, numBytes);
+	}
+
+	public static void putLongNormalizedKey(long value, MemorySegment target, int offset,
+			int numBytes) {
+		NormalizedKeyUtil.putLongNormalizedKey(value, target, offset, numBytes);
+	}
+
+	/**
+	 * See http://stereopsis.com/radix.html for more details.
+	 */
+	public static void putFloatNormalizedKey(float value, MemorySegment target, int offset,
+			int numBytes) {
+		int iValue = Float.floatToIntBits(value);
+		iValue ^= ((iValue >> (Integer.SIZE - 1)) | Integer.MIN_VALUE);
+		NormalizedKeyUtil.putUnsignedIntegerNormalizedKey(iValue, target, offset, numBytes);
+	}
+
+	/**
+	 * See http://stereopsis.com/radix.html for more details.
+	 */
+	public static void putDoubleNormalizedKey(double value, MemorySegment target, int offset,
+			int numBytes) {
+		long lValue = Double.doubleToLongBits(value);
+		lValue ^= ((lValue >> (Long.SIZE - 1)) | Long.MIN_VALUE);
+		NormalizedKeyUtil.putUnsignedLongNormalizedKey(lValue, target, offset, numBytes);
+	}
+
+	public static void putCharNormalizedKey(char value, MemorySegment target, int offset, int numBytes) {
+		NormalizedKeyUtil.putCharNormalizedKey(value, target, offset, numBytes);
+	}
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/SpillChannelManager.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/SpillChannelManager.java
new file mode 100644
index 0000000..06adfca
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/SpillChannelManager.java
@@ -0,0 +1,101 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.runtime.io.disk.iomanager.FileIOChannel;
+
+import java.io.Closeable;
+import java.io.File;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+
+import static org.apache.flink.util.Preconditions.checkArgument;
+
+/**
+ * Channel manager to manage the life cycle of spill channels.
+ */
+public class SpillChannelManager implements Closeable {
+
+	private final HashSet<FileIOChannel.ID> channels;
+	private final HashSet<FileIOChannel> openChannels;
+
+	private volatile boolean closed;
+
+	public SpillChannelManager() {
+		this.channels = new HashSet<>(64);
+		this.openChannels = new HashSet<>(64);
+	}
+
+	/**
+	 * Add a new File channel.
+	 */
+	public synchronized void addChannel(FileIOChannel.ID id) {
+		checkArgument(!closed);
+		channels.add(id);
+	}
+
+	/**
+	 * Open File channels.
+	 */
+	public synchronized void addOpenChannels(List<FileIOChannel> toOpen) {
+		checkArgument(!closed);
+		for (FileIOChannel channel : toOpen) {
+			openChannels.add(channel);
+			channels.remove(channel.getChannelID());
+		}
+	}
+
+	public synchronized void removeChannel(FileIOChannel.ID id) {
+		checkArgument(!closed);
+		channels.remove(id);
+	}
+
+	@Override
+	public synchronized void close() {
+
+		if (this.closed) {
+			return;
+		}
+
+		this.closed = true;
+
+		for (Iterator<FileIOChannel> channels = this.openChannels.iterator(); channels.hasNext(); ) {
+			final FileIOChannel channel = channels.next();
+			channels.remove();
+			try {
+				channel.closeAndDelete();
+			} catch (Throwable ignored) {
+			}
+		}
+
+		for (Iterator<FileIOChannel.ID> channels = this.channels.iterator(); channels.hasNext(); ) {
+			final FileIOChannel.ID channel = channels.next();
+			channels.remove();
+			try {
+				final File f = new File(channel.getPath());
+				if (f.exists()) {
+					f.delete();
+				}
+			} catch (Throwable ignored) {
+			}
+		}
+	}
+
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/compression/BlockCompressionFactory.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/util/MemorySegmentPool.java
similarity index 60%
copy from flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/compression/BlockCompressionFactory.java
copy to flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/util/MemorySegmentPool.java
index a3c1261..94713e5 100644
--- a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/compression/BlockCompressionFactory.java
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/util/MemorySegmentPool.java
@@ -16,15 +16,30 @@
  * limitations under the License.
  */
 
-package org.apache.flink.table.runtime.compression;
+package org.apache.flink.table.runtime.util;
+
+import org.apache.flink.core.memory.MemorySegment;
+import org.apache.flink.core.memory.MemorySegmentSource;
+
+import java.util.Arrays;
+import java.util.List;
 
 /**
- * Each compression codec has a implementation of {@link BlockCompressionFactory}
- * to create compressors and decompressors.
+ * MemorySegment pool.
  */
-public interface BlockCompressionFactory {
+public interface MemorySegmentPool extends MemorySegmentSource {
+
+	int pageSize();
+
+	void returnAll(List<MemorySegment> memory);
+
+	default void returnAll(MemorySegment[] memory) {
+		returnAll(Arrays.asList(memory));
+	}
 
-	BlockCompressor getCompressor();
+	void clear();
 
-	BlockDecompressor getDecompressor();
+	default int remainBuffers() {
+		throw new UnsupportedOperationException();
+	}
 }
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/typeutils/AbstractRowSerializer.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/typeutils/AbstractRowSerializer.java
new file mode 100644
index 0000000..4fe561b
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/typeutils/AbstractRowSerializer.java
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.typeutils;
+
+import org.apache.flink.api.common.typeutils.TypeSerializer;
+import org.apache.flink.runtime.memory.AbstractPagedInputView;
+import org.apache.flink.runtime.memory.AbstractPagedOutputView;
+import org.apache.flink.table.dataformat.BaseRow;
+import org.apache.flink.table.dataformat.BinaryRow;
+
+import java.io.IOException;
+
+/**
+ * Row serializer, provided paged serialize paged method.
+ */
+public abstract class AbstractRowSerializer<T extends BaseRow> extends TypeSerializer<T> {
+
+	/**
+	 * Convert a {@link BaseRow} to a {@link BinaryRow}.
+	 */
+	public abstract BinaryRow baseRowToBinary(T baseRow) throws IOException;
+
+	/**
+	 * Serializes the given record to the given target paged output view. Make specific implementers decide whether
+	 * or not to jump, how many positions jump. If jumps, will skip some offset.
+	 *
+	 * @param record The record to serialize.
+	 * @param target The output view to write the serialized data to.
+	 * @return Returns how much offset is skipped.
+	 * @throws IOException Thrown, if the serialization encountered an I/O related error. Typically raised by the
+	 *                     output view, which may have an underlying I/O channel to which it delegates.
+	 */
+	public int serializeToPages(T record, AbstractPagedOutputView target) throws IOException {
+		serialize(record, target);
+		return 0;
+	}
+
+	/**
+	 * De-serializes a record from the given source paged input view. Make specific implementers decide whether
+	 * or not to jump, how many positions jump. If jumps, will skip some bytes to read.
+	 *
+	 * @param source The input view from which to read the data.
+	 * @return The deserialized element.
+	 *
+	 * @throws IOException Thrown, if the de-serialization encountered an I/O related error. Typically raised by the
+	 *                     input view, which may have an underlying I/O channel from which it reads.
+	 */
+	public T deserializeFromPages(AbstractPagedInputView source) throws IOException {
+		return deserialize(source);
+	}
+
+	/**
+	 * Reuse version of {@link #deserializeFromPages(AbstractPagedInputView)}.
+	 */
+	public T deserializeFromPages(T reuse, AbstractPagedInputView source) throws IOException {
+		return deserialize(reuse, source);
+	}
+
+	/**
+	 * Map a record from the given source paged input view. This method provides a possibility to achieve zero copy,
+	 * you can copy, you can not copy, while you have to properly manage the life cycle of the page.
+	 * Pay attention: Before the end of the visit(Or iterator), pages can not be released.
+	 * @param source The input view from which to read the data.
+	 * @return The deserialized element.
+	 *
+	 * @throws IOException Thrown, if the de-serialization encountered an I/O related error. Typically raised by the
+	 *                     input view, which may have an underlying I/O channel from which it reads.
+	 */
+	public T mapFromPages(AbstractPagedInputView source) throws IOException {
+		return deserialize(source);
+	}
+
+	/**
+	 * Reuse version of {@link #mapFromPages(AbstractPagedInputView)}.
+	 */
+	public T mapFromPages(T reuse, AbstractPagedInputView source) throws IOException {
+		return deserialize(reuse, source);
+	}
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/typeutils/BaseRowSerializer.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/typeutils/BaseRowSerializer.java
index fc2069e..d4f8246 100644
--- a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/typeutils/BaseRowSerializer.java
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/typeutils/BaseRowSerializer.java
@@ -28,6 +28,8 @@ import org.apache.flink.api.java.typeutils.runtime.DataInputViewStream;
 import org.apache.flink.api.java.typeutils.runtime.DataOutputViewStream;
 import org.apache.flink.core.memory.DataInputView;
 import org.apache.flink.core.memory.DataOutputView;
+import org.apache.flink.runtime.memory.AbstractPagedInputView;
+import org.apache.flink.runtime.memory.AbstractPagedOutputView;
 import org.apache.flink.table.dataformat.BaseRow;
 import org.apache.flink.table.dataformat.BinaryRow;
 import org.apache.flink.table.dataformat.BinaryRowWriter;
@@ -44,7 +46,7 @@ import java.util.Arrays;
 /**
  * Serializer for BaseRow.
  */
-public class BaseRowSerializer extends TypeSerializer<BaseRow> {
+public class BaseRowSerializer extends AbstractRowSerializer<BaseRow> {
 
 	private BinaryRowSerializer binarySerializer;
 	private final InternalType[] types;
@@ -135,6 +137,7 @@ public class BaseRowSerializer extends TypeSerializer<BaseRow> {
 	 * Convert base row to binary row.
 	 * TODO modify it to code gen, and reuse BinaryRow&BinaryRowWriter.
 	 */
+	@Override
 	public BinaryRow baseRowToBinary(BaseRow row) {
 		if (row instanceof BinaryRow) {
 			return (BinaryRow) row;
@@ -172,6 +175,38 @@ public class BaseRowSerializer extends TypeSerializer<BaseRow> {
 	}
 
 	@Override
+	public int serializeToPages(BaseRow row, AbstractPagedOutputView target) throws IOException {
+		return binarySerializer.serializeToPages(baseRowToBinary(row), target);
+	}
+
+	@Override
+	public BaseRow deserializeFromPages(AbstractPagedInputView source) throws IOException {
+		throw new UnsupportedOperationException("Not support!");
+	}
+
+	@Override
+	public BaseRow deserializeFromPages(BaseRow reuse,
+			AbstractPagedInputView source) throws IOException {
+		throw new UnsupportedOperationException("Not support!");
+	}
+
+	@Override
+	public BaseRow mapFromPages(AbstractPagedInputView source) throws IOException {
+		//noinspection unchecked
+		return binarySerializer.mapFromPages(source);
+	}
+
+	@Override
+	public BaseRow mapFromPages(BaseRow reuse,
+			AbstractPagedInputView source) throws IOException {
+		if (reuse instanceof BinaryRow) {
+			return binarySerializer.mapFromPages((BinaryRow) reuse, source);
+		} else {
+			throw new UnsupportedOperationException("Not support!");
+		}
+	}
+
+	@Override
 	public boolean equals(Object obj) {
 		if (obj instanceof BaseRowSerializer) {
 			BaseRowSerializer other = (BaseRowSerializer) obj;
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/typeutils/BinaryRowSerializer.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/typeutils/BinaryRowSerializer.java
index 79fb16e..b620a13 100644
--- a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/typeutils/BinaryRowSerializer.java
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/typeutils/BinaryRowSerializer.java
@@ -25,6 +25,8 @@ import org.apache.flink.core.memory.DataInputView;
 import org.apache.flink.core.memory.DataOutputView;
 import org.apache.flink.core.memory.MemorySegment;
 import org.apache.flink.core.memory.MemorySegmentFactory;
+import org.apache.flink.runtime.memory.AbstractPagedInputView;
+import org.apache.flink.runtime.memory.AbstractPagedOutputView;
 import org.apache.flink.table.dataformat.BinaryRow;
 import org.apache.flink.table.util.SegmentsUtil;
 
@@ -35,14 +37,16 @@ import static org.apache.flink.util.Preconditions.checkArgument;
 /**
  * Serializer for {@link BinaryRow}.
  */
-public class BinaryRowSerializer extends TypeSerializer<BinaryRow> {
+public class BinaryRowSerializer extends AbstractRowSerializer<BinaryRow> {
 
 	private static final long serialVersionUID = 1L;
 
 	private final int numFields;
+	private final int fixedLengthPartSize;
 
 	public BinaryRowSerializer(int numFields) {
 		this.numFields = numFields;
+		this.fixedLengthPartSize = BinaryRow.calculateFixPartSizeInBytes(numFields);
 	}
 
 	@Override
@@ -65,6 +69,19 @@ public class BinaryRowSerializer extends TypeSerializer<BinaryRow> {
 		return copy(from, new BinaryRow(numFields));
 	}
 
+	/**
+	 * Copy a page binaryRow to output view.
+	 * @param source source paged input view.
+	 * @param target output view.
+	 */
+	public void copyFromPagesToView(
+			AbstractPagedInputView source, DataOutputView target) throws IOException {
+		checkSkipReadForFixLengthPart(source);
+		int length = source.readInt();
+		target.writeInt(length);
+		target.write(source, length);
+	}
+
 	@Override
 	public BinaryRow copy(BinaryRow from, BinaryRow reuse) {
 		return from.copy(reuse);
@@ -76,6 +93,11 @@ public class BinaryRowSerializer extends TypeSerializer<BinaryRow> {
 	}
 
 	@Override
+	public BinaryRow baseRowToBinary(BinaryRow baseRow) throws IOException {
+		return baseRow;
+	}
+
+	@Override
 	public void serialize(BinaryRow record, DataOutputView target) throws IOException {
 		target.writeInt(record.getSizeInBytes());
 		SegmentsUtil.copyBytesToView(record.getSegments(), record.getOffset(), record.getSizeInBytes(), target);
@@ -106,6 +128,132 @@ public class BinaryRowSerializer extends TypeSerializer<BinaryRow> {
 		return reuse;
 	}
 
+	// ============================ Pages serializers ===================================
+
+	@Override
+	public int serializeToPages(BinaryRow record, AbstractPagedOutputView headerLessView) throws IOException {
+		checkArgument(headerLessView.getHeaderLength() == 0);
+		int skip = checkSkipWriteForFixLengthPart(headerLessView);
+		serialize(record, headerLessView);
+		return skip;
+	}
+
+	@Override
+	public BinaryRow deserializeFromPages(AbstractPagedInputView headerLessView) throws IOException {
+		return deserializeFromPages(createInstance(), headerLessView);
+	}
+
+	@Override
+	public BinaryRow deserializeFromPages(BinaryRow reuse, AbstractPagedInputView headerLessView) throws IOException {
+		checkArgument(headerLessView.getHeaderLength() == 0);
+		checkSkipReadForFixLengthPart(headerLessView);
+		return deserialize(reuse, headerLessView);
+	}
+
+	@Override
+	public BinaryRow mapFromPages(AbstractPagedInputView headerLessView) throws IOException {
+		return mapFromPages(createInstance(), headerLessView);
+	}
+
+	@Override
+	public BinaryRow mapFromPages(BinaryRow reuse, AbstractPagedInputView headerLessView) throws IOException {
+		checkArgument(headerLessView.getHeaderLength() == 0);
+		checkSkipReadForFixLengthPart(headerLessView);
+		pointTo(headerLessView.readInt(), reuse, headerLessView);
+		return reuse;
+	}
+
+	/**
+	 * Point row to memory segments with offset(in the AbstractPagedInputView) and length.
+	 *
+	 * @param length row length.
+	 * @param reuse reuse BinaryRow object.
+	 * @param headerLessView source memory segments container.
+	 */
+	public void pointTo(int length, BinaryRow reuse, AbstractPagedInputView headerLessView) throws IOException {
+		checkArgument(headerLessView.getHeaderLength() == 0);
+		if (length < 0) {
+			throw new IOException(String.format(
+					"Read unexpected bytes in source of positionInSegment[%d] and limitInSegment[%d]",
+					headerLessView.getCurrentPositionInSegment(), headerLessView.getCurrentSegmentLimit()));
+		}
+
+		int remainInSegment = headerLessView.getCurrentSegmentLimit() - headerLessView.getCurrentPositionInSegment();
+		MemorySegment currSeg = headerLessView.getCurrentSegment();
+		int currPosInSeg = headerLessView.getCurrentPositionInSegment();
+		if (remainInSegment >= length) {
+			// all in one segment, that's good.
+			reuse.pointTo(currSeg, currPosInSeg, length);
+			headerLessView.skipBytesToRead(length);
+		} else {
+			pointToMultiSegments(reuse, headerLessView, length, length - remainInSegment, currSeg, currPosInSeg);
+		}
+	}
+
+	private void pointToMultiSegments(
+			BinaryRow reuse, AbstractPagedInputView source, int sizeInBytes,
+			int remainLength, MemorySegment currSeg, int currPosInSeg) throws IOException {
+
+		int segmentSize = currSeg.size();
+		int div = remainLength / segmentSize;
+		int remainder = remainLength - segmentSize * div; // equal to p % q
+		int varSegSize = remainder == 0 ? div : div + 1;
+
+		MemorySegment[] segments = new MemorySegment[varSegSize + 1];
+		segments[0] = currSeg;
+		for (int i = 1; i <= varSegSize; i++) {
+			source.advance();
+			segments[i] = source.getCurrentSegment();
+		}
+
+		// The remaining is 0. There is no next Segment at this time. The current Segment is
+		// all the data of this row, so we need to skip segmentSize bytes to read. We can't
+		// jump directly to the next Segment. Because maybe there are no segment in later.
+		int remainLenInLastSeg = remainder == 0 ? segmentSize : remainder;
+		source.skipBytesToRead(remainLenInLastSeg);
+		reuse.pointTo(segments, currPosInSeg, sizeInBytes);
+	}
+
+	/**
+	 * We need skip bytes to write when the remain bytes of current segment is not
+	 * enough to write binary row fixed part.
+	 * See {@link BinaryRow}.
+	 */
+	private int checkSkipWriteForFixLengthPart(AbstractPagedOutputView out) throws IOException {
+		// skip if there is no enough size.
+		int available = out.getSegmentSize() - out.getCurrentPositionInSegment();
+		if (available < getSerializedRowFixedPartLength()) {
+			out.advance();
+			return available;
+		}
+		return 0;
+	}
+
+	/**
+	 * We need skip bytes to read when the remain bytes of current segment is not
+	 * enough to write binary row fixed part.
+	 * See {@link BinaryRow}.
+	 */
+	public void checkSkipReadForFixLengthPart(AbstractPagedInputView source) throws IOException {
+		// skip if there is no enough size.
+		// Note: Use currentSegmentLimit instead of segmentSize.
+		int available = source.getCurrentSegmentLimit() - source.getCurrentPositionInSegment();
+		if (available < getSerializedRowFixedPartLength()) {
+			source.advance();
+		}
+	}
+
+	/**
+	 * Return fixed part length to serialize one row.
+	 */
+	public int getSerializedRowFixedPartLength() {
+		return getFixedLengthPartSize() + 4; // ADD 4 size length.
+	}
+
+	public int getFixedLengthPartSize() {
+		return fixedLengthPartSize;
+	}
+
 	@Override
 	public void copy(DataInputView source, DataOutputView target) throws IOException {
 		int length = source.readInt();
diff --git a/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/dataformat/BinaryRowTest.java b/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/dataformat/BinaryRowTest.java
index 2881995..1803e5a 100644
--- a/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/dataformat/BinaryRowTest.java
+++ b/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/dataformat/BinaryRowTest.java
@@ -22,14 +22,18 @@ import org.apache.flink.api.common.ExecutionConfig;
 import org.apache.flink.api.common.typeutils.base.StringSerializer;
 import org.apache.flink.core.memory.MemorySegment;
 import org.apache.flink.core.memory.MemorySegmentFactory;
+import org.apache.flink.runtime.io.disk.RandomAccessInputView;
+import org.apache.flink.runtime.io.disk.RandomAccessOutputView;
 import org.apache.flink.table.type.InternalTypes;
 import org.apache.flink.table.typeutils.BaseRowSerializer;
+import org.apache.flink.table.typeutils.BinaryRowSerializer;
 
 import org.junit.Assert;
 import org.junit.Test;
 
 import java.io.IOException;
 import java.math.BigDecimal;
+import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.Random;
 import java.util.Set;
@@ -159,6 +163,79 @@ public class BinaryRowTest {
 		}
 	}
 
+	@Test
+	public void testPagesSer() throws IOException {
+		MemorySegment[] memorySegments = new MemorySegment[5];
+		ArrayList<MemorySegment> memorySegmentList = new ArrayList<>();
+		for (int i = 0; i < 5; i++) {
+			memorySegments[i] = MemorySegmentFactory.wrap(new byte[64]);
+			memorySegmentList.add(memorySegments[i]);
+		}
+
+		{
+			// multi memorySegments
+			String str = "啦啦啦啦啦我是快乐的粉刷匠,啦啦啦啦啦我是快乐的粉刷匠," +
+					"啦啦啦啦啦我是快乐的粉刷匠。";
+			BinaryRow row = new BinaryRow(1);
+			BinaryRowWriter writer = new BinaryRowWriter(row);
+			writer.writeString(0, BinaryString.fromString(str));
+			writer.complete();
+
+			RandomAccessOutputView out = new RandomAccessOutputView(memorySegments, 64);
+			BinaryRowSerializer serializer = new BinaryRowSerializer(1);
+			serializer.serializeToPages(row, out);
+
+			BinaryRow mapRow = serializer.mapFromPages(new RandomAccessInputView(memorySegmentList, 64));
+			writer.reset();
+			writer.writeString(0, mapRow.getString(0));
+			writer.complete();
+			assertEquals(str, row.getString(0).toString());
+
+			BinaryRow deserRow = serializer.deserializeFromPages(new RandomAccessInputView(memorySegmentList, 64));
+			writer.reset();
+			writer.writeString(0, deserRow.getString(0));
+			writer.complete();
+			assertEquals(str, row.getString(0).toString());
+		}
+
+		{
+			// multi memorySegments
+			String str1 = "啦啦啦啦啦我是快乐的粉刷匠,啦啦啦啦啦我是快乐的粉刷匠," +
+					"啦啦啦啦啦我是快乐的粉刷匠。";
+			String str2 = "啦啦啦啦啦我是快乐的粉刷匠。";
+			BinaryRow row = new BinaryRow(2);
+			BinaryRowWriter writer = new BinaryRowWriter(row);
+			writer.writeString(0, BinaryString.fromString(str1));
+			writer.writeString(1, BinaryString.fromString(str2));
+			writer.complete();
+
+			RandomAccessOutputView out = new RandomAccessOutputView(memorySegments, 64);
+			out.skipBytesToWrite(40);
+			BinaryRowSerializer serializer = new BinaryRowSerializer(2);
+			serializer.serializeToPages(row, out);
+
+			RandomAccessInputView in = new RandomAccessInputView(memorySegmentList, 64);
+			in.skipBytesToRead(40);
+			BinaryRow mapRow = serializer.mapFromPages(in);
+			writer.reset();
+			writer.writeString(0, mapRow.getString(0));
+			writer.writeString(1, mapRow.getString(1));
+			writer.complete();
+			assertEquals(str1, row.getString(0).toString());
+			assertEquals(str2, row.getString(1).toString());
+
+			in = new RandomAccessInputView(memorySegmentList, 64);
+			in.skipBytesToRead(40);
+			BinaryRow deserRow = serializer.deserializeFromPages(in);
+			writer.reset();
+			writer.writeString(0, deserRow.getString(0));
+			writer.writeString(1, deserRow.getString(1));
+			writer.complete();
+			assertEquals(str1, row.getString(0).toString());
+			assertEquals(str2, row.getString(1).toString());
+		}
+	}
+
 	private void assertTestWriterRow(BinaryRow row) {
 		assertEquals("1", row.getString(0).toString());
 		assertEquals(88, row.getInt(8));
diff --git a/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/dataformat/BinaryStringTest.java b/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/dataformat/BinaryStringTest.java
new file mode 100644
index 0000000..1b78155
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/dataformat/BinaryStringTest.java
@@ -0,0 +1,259 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.	See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.	You may obtain a copy of the License at
+ *
+ *		http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.dataformat;
+
+import org.apache.flink.core.memory.MemorySegment;
+import org.apache.flink.core.memory.MemorySegmentFactory;
+import org.apache.flink.table.runtime.sort.SortUtil;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Random;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.apache.flink.table.dataformat.BinaryString.blankString;
+import static org.apache.flink.table.dataformat.BinaryString.fromBytes;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Test of {@link BinaryString}.
+ *
+ * <p>Caution that you must construct a string by {@link #fromString} to cover all the
+ * test cases.
+ *
+ */
+@RunWith(Parameterized.class)
+public class BinaryStringTest {
+
+	private BinaryString empty = fromString("");
+
+	private final Mode mode;
+
+	public BinaryStringTest(Mode mode) {
+		this.mode = mode;
+	}
+
+	@Parameterized.Parameters(name = "{0}")
+	public static List<Mode> getVarSeg() {
+		return Arrays.asList(Mode.ONE_SEG, Mode.MULTI_SEGS, Mode.STRING, Mode.RANDOM);
+	}
+
+	private enum Mode {
+		ONE_SEG, MULTI_SEGS, STRING, RANDOM
+	}
+
+	private BinaryString fromString(String str) {
+		BinaryString string = BinaryString.fromString(str);
+
+		Mode mode = this.mode;
+
+		if (mode == Mode.RANDOM) {
+			int rnd = new Random().nextInt(3);
+			if (rnd == 0) {
+				mode = Mode.ONE_SEG;
+			} else if (rnd == 1) {
+				mode = Mode.MULTI_SEGS;
+			} else if (rnd == 2) {
+				mode = Mode.STRING;
+			}
+		}
+
+		if (mode == Mode.STRING) {
+			return string;
+		}
+		if (mode == Mode.ONE_SEG || string.getSizeInBytes() < 2) {
+			string.ensureMaterialized();
+			return string;
+		} else {
+			int numBytes = string.getSizeInBytes();
+			int pad = new Random().nextInt(5);
+			int numBytesWithPad = numBytes + pad;
+			int segSize = numBytesWithPad / 2 + 1;
+			byte[] bytes1 = new byte[segSize];
+			byte[] bytes2 = new byte[segSize];
+			if (segSize - pad > 0 && numBytes >= segSize - pad) {
+				string.getSegments()[0].get(
+						0, bytes1, pad, segSize - pad);
+			}
+			string.getSegments()[0].get(segSize - pad, bytes2, 0, numBytes - segSize + pad);
+			return BinaryString.fromAddress(
+					new MemorySegment[] {
+							MemorySegmentFactory.wrap(bytes1),
+							MemorySegmentFactory.wrap(bytes2)
+					}, pad, numBytes);
+		}
+	}
+
+	private void checkBasic(String str, int len) {
+		BinaryString s1 = fromString(str);
+		BinaryString s2 = fromBytes(str.getBytes(StandardCharsets.UTF_8));
+		// assertEquals(s1.numChars(), len);
+		// assertEquals(s2.numChars(), len);
+
+		assertEquals(s1.toString(), str);
+		assertEquals(s2.toString(), str);
+		assertEquals(s1, s2);
+
+		assertEquals(s1.hashCode(), s2.hashCode());
+
+		assertEquals(0, s1.compareTo(s2));
+
+		// assertTrue(s1.contains(s2));
+		// assertTrue(s2.contains(s1));
+		// assertTrue(s1.startsWith(s1));
+		// assertTrue(s1.endsWith(s1));
+	}
+
+	@Test
+	public void basicTest() {
+		checkBasic("", 0);
+		checkBasic(",", 1);
+		checkBasic("hello", 5);
+		checkBasic("hello world", 11);
+		checkBasic("Flink中文社区", 9);
+		checkBasic("中 文 社 区", 7);
+
+		checkBasic("¡", 1); // 2 bytes char
+		checkBasic("ку", 2); // 2 * 2 bytes chars
+		checkBasic("︽﹋%", 3); // 3 * 3 bytes chars
+		checkBasic("\uD83E\uDD19", 1); // 4 bytes char
+	}
+
+	@Test
+	public void emptyStringTest() {
+		assertEquals(empty, fromString(""));
+		assertEquals(empty, fromBytes(new byte[0]));
+		// assertEquals(0, empty.numChars());
+		assertEquals(0, empty.getSizeInBytes());
+	}
+
+	@Test
+	public void compareTo() {
+		assertEquals(0, fromString("   ").compareTo(blankString(3)));
+		assertTrue(fromString("").compareTo(fromString("a")) < 0);
+		assertTrue(fromString("abc").compareTo(fromString("ABC")) > 0);
+		assertTrue(fromString("abc0").compareTo(fromString("abc")) > 0);
+		assertEquals(0, fromString("abcabcabc").compareTo(fromString("abcabcabc")));
+		assertTrue(fromString("aBcabcabc").compareTo(fromString("Abcabcabc")) > 0);
+		assertTrue(fromString("Abcabcabc").compareTo(fromString("abcabcabC")) < 0);
+		assertTrue(fromString("abcabcabc").compareTo(fromString("abcabcabC")) > 0);
+
+		assertTrue(fromString("abc").compareTo(fromString("世界")) < 0);
+		assertTrue(fromString("你好").compareTo(fromString("世界")) > 0);
+		assertTrue(fromString("你好123").compareTo(fromString("你好122")) > 0);
+
+		MemorySegment segment1 = MemorySegmentFactory.allocateUnpooledSegment(1024);
+		MemorySegment segment2 = MemorySegmentFactory.allocateUnpooledSegment(1024);
+		SortUtil.putBinaryStringNormalizedKey(fromString("abcabcabc"), segment1, 0, 9);
+		SortUtil.putBinaryStringNormalizedKey(fromString("abcabcabC"), segment2, 0, 9);
+		assertTrue(segment1.compare(segment2, 0, 0, 9) > 0);
+		SortUtil.putBinaryStringNormalizedKey(fromString("abcab"), segment1, 0, 9);
+		assertTrue(segment1.compare(segment2, 0, 0, 9) < 0);
+	}
+
+	@Test
+	public void testMultiSegments() {
+
+		// prepare
+		MemorySegment[] segments1 = new MemorySegment[2];
+		segments1[0] = MemorySegmentFactory.wrap(new byte[10]);
+		segments1[1] = MemorySegmentFactory.wrap(new byte[10]);
+		segments1[0].put(5, "abcde".getBytes(UTF_8), 0, 5);
+		segments1[1].put(0, "aaaaa".getBytes(UTF_8), 0, 5);
+
+		MemorySegment[] segments2 = new MemorySegment[2];
+		segments2[0] = MemorySegmentFactory.wrap(new byte[5]);
+		segments2[1] = MemorySegmentFactory.wrap(new byte[5]);
+		segments2[0].put(0, "abcde".getBytes(UTF_8), 0, 5);
+		segments2[1].put(0, "b".getBytes(UTF_8), 0, 1);
+
+		// test go ahead both
+		BinaryString binaryString1 = BinaryString.fromAddress(segments1, 5, 10);
+		BinaryString binaryString2 = BinaryString.fromAddress(segments2, 0, 6);
+		assertEquals("abcdeaaaaa", binaryString1.toString());
+		assertEquals("abcdeb", binaryString2.toString());
+		assertEquals(-1, binaryString1.compareTo(binaryString2));
+
+		// test needCompare == len
+		binaryString1 = BinaryString.fromAddress(segments1, 5, 5);
+		binaryString2 = BinaryString.fromAddress(segments2, 0, 5);
+		assertEquals("abcde", binaryString1.toString());
+		assertEquals("abcde", binaryString2.toString());
+		assertEquals(0, binaryString1.compareTo(binaryString2));
+
+		// test find the first segment of this string
+		binaryString1 = BinaryString.fromAddress(segments1, 10, 5);
+		binaryString2 = BinaryString.fromAddress(segments2, 0, 5);
+		assertEquals("aaaaa", binaryString1.toString());
+		assertEquals("abcde", binaryString2.toString());
+		assertEquals(-1, binaryString1.compareTo(binaryString2));
+		assertEquals(1, binaryString2.compareTo(binaryString1));
+
+		// test go ahead single
+		segments2 = new MemorySegment[]{MemorySegmentFactory.wrap(new byte[10])};
+		segments2[0].put(4, "abcdeb".getBytes(UTF_8), 0, 6);
+		binaryString1 = BinaryString.fromAddress(segments1, 5, 10);
+		binaryString2 = BinaryString.fromAddress(segments2, 4, 6);
+		assertEquals("abcdeaaaaa", binaryString1.toString());
+		assertEquals("abcdeb", binaryString2.toString());
+		assertEquals(-1, binaryString1.compareTo(binaryString2));
+		assertEquals(1, binaryString2.compareTo(binaryString1));
+
+	}
+
+	@Test
+	public void testEmptyString() {
+		BinaryString str2 = fromString("hahahahah");
+		BinaryString str3 = new BinaryString(null);
+		{
+			MemorySegment[] segments = new MemorySegment[2];
+			segments[0] = MemorySegmentFactory.wrap(new byte[10]);
+			segments[1] = MemorySegmentFactory.wrap(new byte[10]);
+			str3.pointTo(segments, 15, 0);
+		}
+
+		assertTrue(BinaryString.EMPTY_UTF8.compareTo(str2) < 0);
+		assertTrue(str2.compareTo(BinaryString.EMPTY_UTF8) > 0);
+
+		assertTrue(BinaryString.EMPTY_UTF8.compareTo(str3) == 0);
+		assertTrue(str3.compareTo(BinaryString.EMPTY_UTF8) == 0);
+
+		assertFalse(BinaryString.EMPTY_UTF8.equals(str2));
+		assertFalse(str2.equals(BinaryString.EMPTY_UTF8));
+
+		assertTrue(BinaryString.EMPTY_UTF8.equals(str3));
+		assertTrue(str3.equals(BinaryString.EMPTY_UTF8));
+	}
+
+	@Test
+	public void testLazy() {
+		String javaStr = "haha";
+		BinaryString str = BinaryString.fromString(javaStr);
+		str.ensureMaterialized();
+
+		// check reference same.
+		assertTrue(str.toString() == javaStr);
+	}
+}
diff --git a/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/runtime/sort/BinaryExternalSorterTest.java b/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/runtime/sort/BinaryExternalSorterTest.java
new file mode 100644
index 0000000..8b389c5
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/runtime/sort/BinaryExternalSorterTest.java
@@ -0,0 +1,420 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.runtime.io.disk.iomanager.IOManager;
+import org.apache.flink.runtime.io.disk.iomanager.IOManagerAsync;
+import org.apache.flink.runtime.memory.MemoryManager;
+import org.apache.flink.table.api.TableConfigOptions;
+import org.apache.flink.table.dataformat.BaseRow;
+import org.apache.flink.table.dataformat.BinaryRow;
+import org.apache.flink.table.dataformat.BinaryRowWriter;
+import org.apache.flink.table.dataformat.BinaryString;
+import org.apache.flink.table.typeutils.AbstractRowSerializer;
+import org.apache.flink.table.typeutils.BinaryRowSerializer;
+import org.apache.flink.util.MutableObjectIterator;
+
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+/**
+ * Sort test for binary row.
+ */
+@RunWith(Parameterized.class)
+public class BinaryExternalSorterTest {
+
+	private static final int MEMORY_SIZE = 1024 * 1024 * 32;
+	private static final Logger LOG = LoggerFactory.getLogger(BinaryExternalSorterTest.class);
+	private IOManager ioManager;
+	private MemoryManager memoryManager;
+	private BinaryRowSerializer serializer;
+	private Configuration conf;
+
+	public BinaryExternalSorterTest(
+			boolean spillCompress,
+			boolean asyncMerge) {
+		ioManager = new IOManagerAsync();
+		conf = new Configuration();
+		if (!spillCompress) {
+			conf.setBoolean(TableConfigOptions.SQL_EXEC_SPILL_COMPRESSION_ENABLED, false);
+		}
+		if (asyncMerge) {
+			conf.setBoolean(TableConfigOptions.SQL_EXEC_SORT_ASYNC_MERGE_ENABLED, true);
+		}
+	}
+
+	@Parameterized.Parameters(name = "spillCompress-{0} asyncMerge-{1}")
+	public static Collection<Boolean[]> parameters() {
+		return Arrays.asList(
+				new Boolean[]{false, false},
+				new Boolean[]{false, true},
+				new Boolean[]{true, false},
+				new Boolean[]{true, true});
+	}
+
+	private static String getString(int count) {
+		StringBuilder builder = new StringBuilder();
+		for (int i = 0; i < 8; i++) {
+			builder.append(count);
+		}
+		return builder.toString();
+	}
+
+	@SuppressWarnings("unchecked")
+	@Before
+	public void beforeTest() {
+		this.memoryManager = new MemoryManager(MEMORY_SIZE, 1);
+		this.serializer = new BinaryRowSerializer(2);
+		this.conf.setInteger(TableConfigOptions.SQL_EXEC_SORT_FILE_HANDLES_MAX_NUM, 128);
+	}
+
+	@After
+	public void afterTest() {
+		this.ioManager.shutdown();
+		if (!this.ioManager.isProperlyShutDown()) {
+			Assert.fail("I/O Manager was not properly shut down.");
+		}
+
+		if (this.memoryManager != null) {
+			Assert.assertTrue("Memory leak: not all segments have been returned to the memory manager.",
+					this.memoryManager.verifyEmpty());
+			this.memoryManager.shutdown();
+			this.memoryManager = null;
+		}
+	}
+
+	@Test
+	public void testSortTwoBufferInMemory() throws Exception {
+
+		int size = 1_000_000;
+
+		MockBinaryRowReader reader = new MockBinaryRowReader(size);
+
+		LOG.debug("initializing sortmerger");
+
+		//there are two sort buffer if sortMemory > 100 * 1024 * 1024.
+		MemoryManager memoryManager = new MemoryManager(1024 * 1024 * 101, 1);
+		long minMemorySize = memoryManager.computeNumberOfPages(1) * MemoryManager.DEFAULT_PAGE_SIZE;
+		BinaryExternalSorter sorter = new BinaryExternalSorter(
+				new Object(),
+				memoryManager,
+				minMemorySize,
+				this.ioManager, (AbstractRowSerializer) serializer, serializer,
+				IntNormalizedKeyComputer.INSTANCE, IntRecordComparator.INSTANCE,
+				conf, 1f);
+		sorter.startThreads();
+		sorter.write(reader);
+
+		MutableObjectIterator<BinaryRow> iterator = sorter.getIterator();
+
+		BinaryRow next = serializer.createInstance();
+		for (int i = 0; i < size; i++) {
+			next = iterator.next(next);
+			Assert.assertEquals(i, next.getInt(0));
+			Assert.assertEquals(getString(i), next.getString(1).toString());
+		}
+
+		sorter.close();
+		Assert.assertTrue(memoryManager.verifyEmpty());
+		memoryManager.shutdown();
+	}
+
+	@Test
+	public void testSort() throws Exception {
+
+		int size = 10_000;
+
+		MockBinaryRowReader reader = new MockBinaryRowReader(size);
+
+		LOG.debug("initializing sortmerger");
+
+		long minMemorySize = memoryManager.computeNumberOfPages(0.9) * MemoryManager.DEFAULT_PAGE_SIZE;
+		BinaryExternalSorter sorter = new BinaryExternalSorter(
+				new Object(),
+				this.memoryManager,
+				minMemorySize,
+				this.ioManager, (AbstractRowSerializer) serializer, serializer,
+				IntNormalizedKeyComputer.INSTANCE, IntRecordComparator.INSTANCE,
+				conf, 0.7f);
+		sorter.startThreads();
+		sorter.write(reader);
+
+		MutableObjectIterator<BinaryRow> iterator = sorter.getIterator();
+
+		BinaryRow next = serializer.createInstance();
+		for (int i = 0; i < size; i++) {
+			next = iterator.next(next);
+			Assert.assertEquals(i, next.getInt(0));
+			Assert.assertEquals(getString(i), next.getString(1).toString());
+		}
+
+		sorter.close();
+	}
+
+	@Test
+	public void testSortIntStringWithRepeat() throws Exception {
+
+		int size = 10_000;
+
+		LOG.debug("initializing sortmerger");
+
+		long minMemorySize = memoryManager.computeNumberOfPages(0.9) * MemoryManager.DEFAULT_PAGE_SIZE;
+		BinaryExternalSorter sorter = new BinaryExternalSorter(
+				new Object(),
+				this.memoryManager,
+				minMemorySize,
+				this.ioManager, (AbstractRowSerializer) serializer, serializer,
+				new IntNormalizedKeyComputer() {
+					@Override
+					public boolean isKeyFullyDetermines() {
+						return false;
+					}
+				},
+				IntRecordComparator.INSTANCE,
+				conf, 0.7f);
+		sorter.startThreads();
+		sorter.write(new MockBinaryRowReader(size));
+		sorter.write(new MockBinaryRowReader(size));
+		sorter.write(new MockBinaryRowReader(size));
+
+		MutableObjectIterator<BinaryRow> iterator = sorter.getIterator();
+
+		BinaryRow next = serializer.createInstance();
+		for (int i = 0; i < size; i++) {
+			for (int j = 0; j < 3; j++) {
+				next = iterator.next(next);
+				Assert.assertEquals(i, next.getInt(0));
+				Assert.assertEquals(getString(i), next.getString(1).toString());
+			}
+		}
+
+		sorter.close();
+	}
+
+	@Test
+	public void testSpilling() throws Exception {
+
+		int size = 1000_000;
+
+		MockBinaryRowReader reader = new MockBinaryRowReader(size);
+
+		LOG.debug("initializing sortmerger");
+
+		long minMemorySize = memoryManager.computeNumberOfPages(0.1) * MemoryManager.DEFAULT_PAGE_SIZE;
+		BinaryExternalSorter sorter = new BinaryExternalSorter(
+				new Object(),
+				this.memoryManager,
+				minMemorySize,
+				this.ioManager, (AbstractRowSerializer) serializer, serializer,
+				IntNormalizedKeyComputer.INSTANCE, IntRecordComparator.INSTANCE,
+				conf, 0.7f);
+		sorter.startThreads();
+		sorter.write(reader);
+
+		MutableObjectIterator<BinaryRow> iterator = sorter.getIterator();
+
+		BinaryRow next = serializer.createInstance();
+		for (int i = 0; i < size; i++) {
+			next = iterator.next(next);
+			Assert.assertEquals(i, next.getInt(0));
+			Assert.assertEquals(getString(i), next.getString(1).toString());
+		}
+
+		sorter.close();
+	}
+
+	@Test
+	public void testSpillingDesc() throws Exception {
+
+		int size = 1000_000;
+
+		MockBinaryRowReader reader = new MockBinaryRowReader(size);
+
+		LOG.debug("initializing sortmerger");
+
+		long minMemorySize = memoryManager.computeNumberOfPages(0.1) * MemoryManager.DEFAULT_PAGE_SIZE;
+		BinaryExternalSorter sorter = new BinaryExternalSorter(
+				new Object(),
+				this.memoryManager,
+				minMemorySize,
+				this.ioManager, (AbstractRowSerializer) serializer, serializer,
+				new IntNormalizedKeyComputer() {
+					@Override
+					public boolean invertKey() {
+						return true;
+					}
+				},
+				new IntRecordComparator() {
+					@Override
+					public int compare(BaseRow o1, BaseRow o2) {
+						return -super.compare(o1, o2);
+					}
+				},
+				conf, 0.7f);
+		sorter.startThreads();
+		sorter.write(reader);
+
+		MutableObjectIterator<BinaryRow> iterator = sorter.getIterator();
+
+		List<Tuple2<Integer, String>> data = new ArrayList<>();
+		for (int i = 0; i < size; i++) {
+			data.add(new Tuple2<>(i, getString(i)));
+		}
+		data.sort((o1, o2) -> -o1.f0.compareTo(o2.f0));
+
+		BinaryRow next = serializer.createInstance();
+		for (int i = 0; i < size; i++) {
+			next = iterator.next(next);
+			Assert.assertEquals((int) data.get(i).f0, next.getInt(0));
+			Assert.assertEquals(data.get(i).f1, next.getString(1).toString());
+		}
+
+		sorter.close();
+	}
+
+	@Test
+	public void testMergeManyTimes() throws Exception {
+
+		int size = 1000_000;
+
+		MockBinaryRowReader reader = new MockBinaryRowReader(size);
+
+		LOG.debug("initializing sortmerger");
+
+		long minMemorySize = memoryManager.computeNumberOfPages(0.01) * MemoryManager.DEFAULT_PAGE_SIZE;
+		conf.setInteger(TableConfigOptions.SQL_EXEC_SORT_FILE_HANDLES_MAX_NUM, 8);
+
+		BinaryExternalSorter sorter = new BinaryExternalSorter(
+				new Object(),
+				this.memoryManager,
+				minMemorySize,
+				this.ioManager, (AbstractRowSerializer) serializer, serializer,
+				IntNormalizedKeyComputer.INSTANCE, IntRecordComparator.INSTANCE,
+				conf, 0.7f);
+		sorter.startThreads();
+		sorter.write(reader);
+
+		MutableObjectIterator<BinaryRow> iterator = sorter.getIterator();
+
+		BinaryRow next = serializer.createInstance();
+		for (int i = 0; i < size; i++) {
+			next = iterator.next(next);
+			Assert.assertEquals(i, next.getInt(0));
+			Assert.assertEquals(getString(i), next.getString(1).toString());
+		}
+
+		sorter.close();
+	}
+
+	@Test
+	public void testSpillingRandom() throws Exception {
+
+		int size = 1000_000;
+
+		MockBinaryRowReader reader = new MockBinaryRowReader(size);
+
+		LOG.debug("initializing sortmerger");
+
+		long minMemorySize = memoryManager.computeNumberOfPages(0.1) * MemoryManager.DEFAULT_PAGE_SIZE;
+		BinaryExternalSorter sorter = new BinaryExternalSorter(
+				new Object(),
+				this.memoryManager,
+				minMemorySize,
+				this.ioManager, (AbstractRowSerializer) serializer, serializer,
+				IntNormalizedKeyComputer.INSTANCE, IntRecordComparator.INSTANCE,
+				conf, 0.7f);
+		sorter.startThreads();
+
+		List<BinaryRow> data = new ArrayList<>();
+		BinaryRow row = serializer.createInstance();
+		for (int i = 0; i < size; i++) {
+			row = reader.next(row);
+			data.add(row.copy());
+		}
+
+		Collections.shuffle(data);
+
+		for (int i = 0; i < size; i++) {
+			sorter.write(data.get(i));
+		}
+
+		MutableObjectIterator<BinaryRow> iterator = sorter.getIterator();
+
+		data.sort(Comparator.comparingInt(o -> o.getInt(0)));
+
+		BinaryRow next = serializer.createInstance();
+		for (int i = 0; i < size; i++) {
+			next = iterator.next(next);
+			Assert.assertEquals(data.get(i).getInt(0), next.getInt(0));
+			Assert.assertEquals(data.get(i).getString(1), next.getString(1));
+		}
+
+		sorter.close();
+	}
+
+	/**
+	 * Mock reader for binary row.
+	 */
+	public class MockBinaryRowReader implements MutableObjectIterator<BinaryRow> {
+
+		private int size;
+		private int count;
+		private BinaryRow row;
+		private BinaryRowWriter writer;
+
+		public MockBinaryRowReader(int size) {
+			this.size = size;
+			this.row = new BinaryRow(2);
+			this.writer = new BinaryRowWriter(row);
+		}
+
+		@Override
+		public BinaryRow next(BinaryRow reuse) {
+			return next();
+		}
+
+		@Override
+		public BinaryRow next() {
+			if (count >= size) {
+				return null;
+			}
+			writer.reset();
+			writer.writeInt(0, count);
+			writer.writeString(1, BinaryString.fromString(getString(count)));
+			writer.complete();
+			count++;
+			return row;
+		}
+	}
+}
diff --git a/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/runtime/sort/BinaryMergeIteratorTest.java b/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/runtime/sort/BinaryMergeIteratorTest.java
new file mode 100644
index 0000000..30bde3e
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/runtime/sort/BinaryMergeIteratorTest.java
@@ -0,0 +1,176 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.api.common.typeutils.TypeComparator;
+import org.apache.flink.api.common.typeutils.base.IntComparator;
+import org.apache.flink.table.dataformat.BinaryRow;
+import org.apache.flink.table.dataformat.BinaryRowWriter;
+import org.apache.flink.table.dataformat.BinaryString;
+import org.apache.flink.table.typeutils.BinaryRowSerializer;
+import org.apache.flink.util.MutableObjectIterator;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Test of {@link BinaryMergeIterator}.
+ */
+public class BinaryMergeIteratorTest {
+
+	private RecordComparator comparator;
+	private BinaryRowSerializer serializer;
+
+	@Before
+	public void setup() throws InstantiationException, IllegalAccessException {
+		serializer = new BinaryRowSerializer(2);
+		comparator = IntRecordComparator.INSTANCE;
+	}
+
+	private MutableObjectIterator<BinaryRow> newIterator(final int[] keys, final String[] values) {
+
+		BinaryRow row = serializer.createInstance();
+		BinaryRowWriter writer = new BinaryRowWriter(row);
+		return new MutableObjectIterator<BinaryRow>() {
+
+			private int current = 0;
+
+			@Override
+			public BinaryRow next(BinaryRow reuse) {
+				if (current < keys.length) {
+					int key = keys[current];
+					String value = values[current];
+					current++;
+					writer.reset();
+					writer.writeInt(0, key);
+					writer.writeString(1, BinaryString.fromString(value));
+					writer.complete();
+					return row;
+				} else {
+					return null;
+				}
+			}
+
+			@Override
+			public BinaryRow next() {
+				throw new RuntimeException();
+			}
+		};
+	}
+
+	@Test
+	public void testOneStream() throws Exception {
+		List<MutableObjectIterator<BinaryRow>> iterators = new ArrayList<>();
+		iterators.add(newIterator(
+				new int[]{1, 2, 4, 5, 10}, new String[]{"1", "2", "4", "5", "10"}));
+
+		final int[] expected = new int[]{1, 2, 4, 5, 10};
+
+		MutableObjectIterator<BinaryRow> iterator =
+				new BinaryMergeIterator<>(
+						iterators,
+						Collections.singletonList(serializer.createInstance()),
+						(o1, o2) -> this.comparator.compare(o1, o2));
+
+		BinaryRow row = serializer.createInstance();
+
+		int pos = 0;
+		while ((row = iterator.next(row)) != null) {
+			Assert.assertEquals(expected[pos++], row.getInt(0));
+		}
+	}
+
+	@Test
+	public void testMergeOfTwoStreams() throws Exception {
+		List<MutableObjectIterator<BinaryRow>> iterators = new ArrayList<>();
+		iterators.add(newIterator(
+				new int[]{1, 2, 4, 5, 10}, new String[]{"1", "2", "4", "5", "10"}));
+		iterators.add(newIterator(
+				new int[]{3, 6, 7, 10, 12}, new String[]{"3", "6", "7", "10", "12"}));
+
+		final int[] expected = new int[]{1, 2, 3, 4, 5, 6, 7, 10, 10, 12};
+
+		MutableObjectIterator<BinaryRow> iterator =
+				new BinaryMergeIterator<>(
+						iterators,
+						reused(2),
+						(o1, o2) -> this.comparator.compare(o1, o2));
+
+		BinaryRow row = serializer.createInstance();
+
+		int pos = 0;
+		while ((row = iterator.next(row)) != null) {
+			Assert.assertEquals(expected[pos++], row.getInt(0));
+		}
+	}
+
+	@Test
+	public void testMergeOfTenStreams() throws Exception {
+		List<MutableObjectIterator<BinaryRow>> iterators = new ArrayList<>();
+		iterators.add(newIterator(
+				new int[]{1, 2, 17, 23, 23}, new String[]{"A", "B", "C", "D", "E"}));
+		iterators.add(newIterator(
+				new int[]{2, 6, 7, 8, 9}, new String[]{"A", "B", "C", "D", "E"}));
+		iterators.add(newIterator(
+				new int[]{4, 10, 11, 11, 12}, new String[]{"A", "B", "C", "D", "E"}));
+		iterators.add(newIterator(
+				new int[]{3, 6, 7, 10, 12}, new String[]{"A", "B", "C", "D", "E"}));
+		iterators.add(newIterator(
+				new int[]{7, 10, 15, 19, 44}, new String[]{"A", "B", "C", "D", "E"}));
+		iterators.add(newIterator(
+				new int[]{6, 6, 11, 17, 18}, new String[]{"A", "B", "C", "D", "E"}));
+		iterators.add(newIterator(
+				new int[]{1, 2, 4, 5, 10}, new String[]{"A", "B", "C", "D", "E"}));
+		iterators.add(newIterator(
+				new int[]{5, 10, 19, 23, 29}, new String[]{"A", "B", "C", "D", "E"}));
+		iterators.add(newIterator(
+				new int[]{9, 9, 9, 9, 9}, new String[]{"A", "B", "C", "D", "E"}));
+		iterators.add(newIterator(
+				new int[]{8, 8, 14, 14, 15}, new String[]{"A", "B", "C", "D", "E"}));
+
+		TypeComparator<Integer> comparator = new IntComparator(true);
+
+		MutableObjectIterator<BinaryRow> iterator =
+				new BinaryMergeIterator<>(
+						iterators,
+						reused(10),
+						(o1, o2) -> this.comparator.compare(o1, o2));
+
+		BinaryRow row = serializer.createInstance();
+
+		int pre = 0;
+		while ((row = iterator.next(row)) != null) {
+			Assert.assertTrue(comparator.compare(row.getInt(0), pre) >= 0);
+			pre = row.getInt(0);
+		}
+	}
+
+	private List<BinaryRow> reused(int size) {
+		ArrayList<BinaryRow> ret = new ArrayList<>(size);
+		for (int i = 0; i < size; i++) {
+			ret.add(serializer.createInstance());
+		}
+		return ret;
+	}
+}
diff --git a/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/runtime/sort/BufferedKVExternalSorterTest.java b/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/runtime/sort/BufferedKVExternalSorterTest.java
new file mode 100644
index 0000000..13356cc
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/runtime/sort/BufferedKVExternalSorterTest.java
@@ -0,0 +1,169 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.core.memory.MemorySegment;
+import org.apache.flink.runtime.io.disk.SimpleCollectingOutputView;
+import org.apache.flink.runtime.io.disk.iomanager.IOManager;
+import org.apache.flink.runtime.io.disk.iomanager.IOManagerAsync;
+import org.apache.flink.runtime.memory.MemoryManager;
+import org.apache.flink.table.api.TableConfigOptions;
+import org.apache.flink.table.dataformat.BinaryRow;
+import org.apache.flink.table.dataformat.BinaryRowWriter;
+import org.apache.flink.table.dataformat.BinaryString;
+import org.apache.flink.table.typeutils.BinaryRowSerializer;
+import org.apache.flink.util.MutableObjectIterator;
+
+import org.apache.commons.lang3.RandomStringUtils;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+
+/**
+ * UT for BufferedKVExternalSorter.
+ */
+@RunWith(Parameterized.class)
+public class BufferedKVExternalSorterTest {
+	private static final int PAGE_SIZE = MemoryManager.DEFAULT_PAGE_SIZE;
+
+	private IOManager ioManager;
+	private BinaryRowSerializer keySerializer;
+	private BinaryRowSerializer valueSerializer;
+	private NormalizedKeyComputer computer;
+	private RecordComparator comparator;
+
+	private int spillNumber;
+	private int recordNumberPerFile;
+
+	private Configuration conf;
+
+	public BufferedKVExternalSorterTest(
+			int spillNumber, int recordNumberPerFile, boolean spillCompress) {
+		ioManager = new IOManagerAsync();
+		conf = new Configuration();
+		conf.setInteger(TableConfigOptions.SQL_EXEC_SORT_FILE_HANDLES_MAX_NUM, 5);
+		if (!spillCompress) {
+			conf.setBoolean(TableConfigOptions.SQL_EXEC_SPILL_COMPRESSION_ENABLED, false);
+		}
+		this.spillNumber = spillNumber;
+		this.recordNumberPerFile = recordNumberPerFile;
+	}
+
+	@Parameterized.Parameters
+	public static List<Object[]> getDataSize() {
+		List<Object[]> paras = new ArrayList<>();
+		paras.add(new Object[]{3, 1000, true});
+		paras.add(new Object[]{3, 1000, false});
+		paras.add(new Object[]{10, 1000, true});
+		paras.add(new Object[]{10, 1000, false});
+		paras.add(new Object[]{10, 10000, true});
+		paras.add(new Object[]{10, 10000, false});
+		return paras;
+	}
+
+	@Before
+	public void beforeTest() throws InstantiationException, IllegalAccessException {
+		this.ioManager = new IOManagerAsync();
+
+		this.keySerializer = new BinaryRowSerializer(2);
+		this.valueSerializer = new BinaryRowSerializer(2);
+
+		this.computer = IntNormalizedKeyComputer.INSTANCE;
+		this.comparator = IntRecordComparator.INSTANCE;
+	}
+
+	@After
+	public void afterTest() {
+		this.ioManager.shutdown();
+		if (!this.ioManager.isProperlyShutDown()) {
+			Assert.fail("I/O Manager was not properly shut down.");
+		}
+	}
+
+	@Test
+	public void test() throws Exception {
+		BufferedKVExternalSorter sorter =
+				new BufferedKVExternalSorter(
+						ioManager, keySerializer, valueSerializer, computer, comparator,
+						PAGE_SIZE, conf);
+		TestMemorySegmentPool pool = new TestMemorySegmentPool(PAGE_SIZE);
+		List<Integer> expected = new ArrayList<>();
+		for (int i = 0; i < spillNumber; i++) {
+			ArrayList<MemorySegment> segments = new ArrayList<>();
+			SimpleCollectingOutputView out =
+					new SimpleCollectingOutputView(segments, pool, PAGE_SIZE);
+			writeKVToBuffer(
+					keySerializer, valueSerializer,
+					out,
+					expected,
+					recordNumberPerFile);
+			sorter.sortAndSpill(segments, recordNumberPerFile, pool);
+		}
+		Collections.sort(expected);
+		MutableObjectIterator<Tuple2<BinaryRow, BinaryRow>> iterator = sorter.getKVIterator();
+		Tuple2<BinaryRow, BinaryRow> kv =
+				new Tuple2<>(keySerializer.createInstance(), valueSerializer.createInstance());
+		int count = 0;
+		while ((kv = iterator.next(kv)) != null) {
+			Assert.assertEquals((int) expected.get(count), kv.f0.getInt(0));
+			Assert.assertEquals(expected.get(count) * -3 + 177, kv.f1.getInt(0));
+			count++;
+		}
+		Assert.assertEquals(expected.size(), count);
+		sorter.close();
+	}
+
+	private void writeKVToBuffer(
+			BinaryRowSerializer keySerializer,
+			BinaryRowSerializer valueSerializer,
+			SimpleCollectingOutputView out,
+			List<Integer> expecteds,
+			int length) throws IOException {
+		Random random = new Random();
+		int stringLength = 30;
+		for (int i = 0; i < length; i++) {
+			BinaryRow key = randomRow(random, stringLength);
+			BinaryRow val = key.copy();
+			val.setInt(0, val.getInt(0) * -3 + 177);
+			expecteds.add(key.getInt(0));
+			keySerializer.serializeToPages(key, out);
+			valueSerializer.serializeToPages(val, out);
+		}
+	}
+
+	public static BinaryRow randomRow(Random random, int stringLength) {
+		BinaryRow row = new BinaryRow(2);
+		BinaryRowWriter writer = new BinaryRowWriter(row);
+		writer.writeInt(0, random.nextInt());
+		writer.writeString(1, BinaryString.fromString(RandomStringUtils.random(stringLength)));
+		writer.complete();
+		return row;
+	}
+}
diff --git a/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/runtime/sort/IntNormalizedKeyComputer.java b/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/runtime/sort/IntNormalizedKeyComputer.java
new file mode 100644
index 0000000..9cad238
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/runtime/sort/IntNormalizedKeyComputer.java
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.core.memory.MemorySegment;
+import org.apache.flink.table.dataformat.BaseRow;
+
+/**
+ * Example for int {@link NormalizedKeyComputer}.
+ */
+public class IntNormalizedKeyComputer extends org.apache.flink.table.runtime.sort.NormalizedKeyComputer {
+
+	public static final IntNormalizedKeyComputer INSTANCE = new IntNormalizedKeyComputer();
+
+	@Override
+	public void putKey(BaseRow record, MemorySegment target, int offset) {
+		// write first null byte.
+		if (record.isNullAt(0)) {
+			SortUtil.minNormalizedKey(target, offset, 5);
+		} else {
+			target.put(offset, (byte) 1);
+			SortUtil.putIntNormalizedKey(record.getInt(0), target, offset + 1, 4);
+		}
+
+		// revert 4 bytes to compare easier.
+		target.putInt(offset, Integer.reverseBytes(target.getInt(offset)));
+	}
+
+	@Override
+	public int compareKey(MemorySegment segI, int offsetI, MemorySegment segJ, int offsetJ) {
+		int int1 = segI.getInt(offsetI);
+		int int2 = segJ.getInt(offsetJ);
+		if (int1 != int2) {
+			return (int1 < int2) ^ (int1 < 0) ^ (int2 < 0) ? -1 : 1;
+		}
+
+		byte byte1 = segI.get(offsetI + 4);
+		byte byte2 = segJ.get(offsetJ + 4);
+		if (byte1 != byte2) {
+			return (byte1 < byte2) ^ (byte1 < 0) ^ (byte2 < 0) ? -1 : 1;
+		}
+		return 0;
+	}
+
+	@Override
+	public void swapKey(MemorySegment segI, int offsetI, MemorySegment segJ, int offsetJ) {
+
+		int temp0 = segI.getInt(offsetI);
+		segI.putInt(offsetI, segJ.getInt(offsetJ));
+		segJ.putInt(offsetJ, temp0);
+
+		byte temp1 = segI.get(offsetI + 4);
+		segI.put(offsetI + 4, segJ.get(offsetJ + 4));
+		segJ.put(offsetJ + 4, temp1);
+
+	}
+
+	@Override
+	public int getNumKeyBytes() {
+		return 5;
+	}
+
+	@Override
+	public boolean isKeyFullyDetermines() {
+		return true;
+	}
+
+	@Override
+	public boolean invertKey() {
+		return false;
+	}
+
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/compression/BlockCompressionFactory.java b/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/runtime/sort/IntRecordComparator.java
similarity index 58%
copy from flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/compression/BlockCompressionFactory.java
copy to flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/runtime/sort/IntRecordComparator.java
index a3c1261..b41de22 100644
--- a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/compression/BlockCompressionFactory.java
+++ b/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/runtime/sort/IntRecordComparator.java
@@ -16,15 +16,28 @@
  * limitations under the License.
  */
 
-package org.apache.flink.table.runtime.compression;
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.table.dataformat.BaseRow;
 
 /**
- * Each compression codec has a implementation of {@link BlockCompressionFactory}
- * to create compressors and decompressors.
+ * Example String {@link RecordComparator}.
  */
-public interface BlockCompressionFactory {
+public class IntRecordComparator extends RecordComparator {
+
+	public static final IntRecordComparator INSTANCE = new IntRecordComparator();
+
+	@Override
+	public int compare(BaseRow o1, BaseRow o2) {
 
-	BlockCompressor getCompressor();
+		boolean null0At1 = o1.isNullAt(0);
+		boolean null0At2 = o2.isNullAt(0);
+		int cmp0 = null0At1 && null0At2 ? 0 :
+				(null0At1 ? -1 : (null0At2 ? 1 : Integer.compare(o1.getInt(0), o2.getInt(0))));
+		if (cmp0 != 0) {
+			return cmp0;
+		}
+		return 0;
+	}
 
-	BlockDecompressor getDecompressor();
 }
diff --git a/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/runtime/sort/SortUtilTest.java b/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/runtime/sort/SortUtilTest.java
new file mode 100644
index 0000000..de2f61e
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/runtime/sort/SortUtilTest.java
@@ -0,0 +1,132 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.core.memory.MemorySegment;
+import org.apache.flink.core.memory.MemorySegmentFactory;
+import org.apache.flink.table.dataformat.BinaryString;
+import org.apache.flink.table.dataformat.Decimal;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.math.BigDecimal;
+import java.util.Arrays;
+import java.util.Random;
+
+/**
+ * Test for {@link SortUtil}.
+ */
+public class SortUtilTest {
+
+	@Test
+	public void testNormalizedKey() {
+		int len = 10;
+		Random random = new Random();
+		MemorySegment[] segments = new MemorySegment[len];
+		MemorySegment[] compareSegs = new MemorySegment[len];
+		for (int i = 0; i < len; i++) {
+			segments[i] = MemorySegmentFactory.allocateUnpooledSegment(20);
+			compareSegs[i] = MemorySegmentFactory.allocateUnpooledSegment(20);
+		}
+
+		{
+			SortUtil.minNormalizedKey(segments[0], 0, 20);
+			SortUtil.maxNormalizedKey(segments[1], 0, 20);
+			for (int i = 0; i < len; i++) {
+				byte[] rndBytes = new byte[20];
+				random.nextBytes(rndBytes);
+				segments[2].put(0, rndBytes);
+				Assert.assertTrue(segments[0].compare(segments[2], 0, 0, 20) <= 0);
+				Assert.assertTrue(segments[1].compare(segments[2], 0, 0, 20) >= 0);
+			}
+		}
+
+		{
+			Decimal[] arr = new Decimal[len];
+			for (int i = 0; i < len; i++) {
+				arr[i] = Decimal.fromBigDecimal(new BigDecimal(random.nextInt()), 18, 0);
+				SortUtil.putDecimalNormalizedKey(arr[i], segments[i], 0, 8);
+			}
+			Arrays.sort(arr, Decimal::compareTo);
+			for (int i = 0; i < len; i++) {
+				SortUtil.putDecimalNormalizedKey(arr[i], compareSegs[i], 0, 8);
+			}
+
+			Arrays.sort(segments, (o1, o2) -> o1.compare(o2, 0, 0, 8));
+			for (int i = 0; i < len; i++) {
+				Assert.assertTrue(compareSegs[i].equalTo(segments[i], 0, 0, 8));
+			}
+		}
+
+		{
+			Float[] arr = new Float[len];
+			for (int i = 0; i < len; i++) {
+				arr[i] = random.nextFloat();
+				SortUtil.putFloatNormalizedKey(arr[i], segments[i], 0, 4);
+			}
+
+			Arrays.sort(arr, Float::compareTo);
+			for (int i = 0; i < len; i++) {
+				SortUtil.putFloatNormalizedKey(arr[i], compareSegs[i], 0, 4);
+			}
+
+			Arrays.sort(segments, (o1, o2) -> o1.compare(o2, 0, 0, 4));
+			for (int i = 0; i < len; i++) {
+				Assert.assertTrue(compareSegs[i].equalTo(segments[i], 0, 0, 4));
+			}
+		}
+
+		{
+			Double[] arr = new Double[len];
+			for (int i = 0; i < len; i++) {
+				arr[i] = random.nextDouble();
+				SortUtil.putDoubleNormalizedKey(arr[i], segments[i], 0, 8);
+			}
+
+			Arrays.sort(arr, Double::compareTo);
+			for (int i = 0; i < len; i++) {
+				SortUtil.putDoubleNormalizedKey(arr[i], compareSegs[i], 0, 8);
+			}
+
+			Arrays.sort(segments, (o1, o2) -> o1.compare(o2, 0, 0, 8));
+			for (int i = 0; i < len; i++) {
+				Assert.assertTrue(compareSegs[i].equalTo(segments[i], 0, 0, 8));
+			}
+		}
+
+		{
+			BinaryString[] arr = new BinaryString[len];
+			for (int i = 0; i < len; i++) {
+				arr[i] = BinaryString.fromString(String.valueOf(random.nextLong()));
+				SortUtil.putBinaryStringNormalizedKey(arr[i], segments[i], 0, 8);
+			}
+
+			Arrays.sort(arr, BinaryString::compareTo);
+			for (int i = 0; i < len; i++) {
+				SortUtil.putBinaryStringNormalizedKey(arr[i], compareSegs[i], 0, 8);
+			}
+
+			Arrays.sort(segments, (o1, o2) -> o1.compare(o2, 0, 0, 8));
+			for (int i = 0; i < len; i++) {
+				Assert.assertTrue(compareSegs[i].equalTo(segments[i], 0, 0, 8));
+			}
+		}
+	}
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/compression/BlockCompressionFactory.java b/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/runtime/sort/TestMemorySegmentPool.java
similarity index 54%
copy from flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/compression/BlockCompressionFactory.java
copy to flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/runtime/sort/TestMemorySegmentPool.java
index a3c1261..c84db7c 100644
--- a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/compression/BlockCompressionFactory.java
+++ b/flink-table/flink-table-runtime-blink/src/test/java/org/apache/flink/table/runtime/sort/TestMemorySegmentPool.java
@@ -16,15 +16,40 @@
  * limitations under the License.
  */
 
-package org.apache.flink.table.runtime.compression;
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.core.memory.MemorySegment;
+import org.apache.flink.core.memory.MemorySegmentFactory;
+import org.apache.flink.table.runtime.util.MemorySegmentPool;
+
+import java.util.List;
 
 /**
- * Each compression codec has a implementation of {@link BlockCompressionFactory}
- * to create compressors and decompressors.
+ * Test pool.
  */
-public interface BlockCompressionFactory {
+public class TestMemorySegmentPool implements MemorySegmentPool {
+
+	private int pageSize;
+
+	public TestMemorySegmentPool(int pageSize) {
+		this.pageSize = pageSize;
+	}
+
+	@Override
+	public int pageSize() {
+		return pageSize;
+	}
+
+	@Override
+	public void returnAll(List<MemorySegment> memory) {
+	}
 
-	BlockCompressor getCompressor();
+	@Override
+	public void clear() {
+	}
 
-	BlockDecompressor getDecompressor();
+	@Override
+	public MemorySegment nextSegment() {
+		return MemorySegmentFactory.wrap(new byte[pageSize]);
+	}
 }