File size: 64,577 Bytes
5a9e79d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
diff --git a/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/OptimizerConfigOptions.java b/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/OptimizerConfigOptions.java
--- a/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/OptimizerConfigOptions.java
+++ b/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/OptimizerConfigOptions.java
@@ -21,11 +21,14 @@
 import org.apache.flink.annotation.PublicEvolving;
 import org.apache.flink.annotation.docs.Documentation;
 import org.apache.flink.configuration.ConfigOption;
+import org.apache.flink.configuration.DescribedEnum;
 import org.apache.flink.configuration.MemorySize;
 import org.apache.flink.configuration.description.Description;
+import org.apache.flink.configuration.description.InlineElement;
 
 import static org.apache.flink.configuration.ConfigOptions.key;
 import static org.apache.flink.configuration.description.TextElement.code;
+import static org.apache.flink.configuration.description.TextElement.text;
 
 /**
  * This class holds configuration constants used by Flink's table planner module.
@@ -158,6 +161,22 @@ public class OptimizerConfigOptions {
                             "A flag to enable or disable the runtime filter. "
                                     + "When it is true, the optimizer will try to inject a runtime filter for eligible join.");
 
+    @Documentation.TableOption(execMode = Documentation.ExecMode.BATCH)
+    public static final ConfigOption<AdaptiveBroadcastJoinStrategy>
+            TABLE_OPTIMIZER_ADAPTIVE_BROADCAST_JOIN_STRATEGY =
+                    key("table.optimizer.adaptive-broadcast-join.strategy")
+                            .enumType(AdaptiveBroadcastJoinStrategy.class)
+                            .defaultValue(AdaptiveBroadcastJoinStrategy.NONE)
+                            .withDescription(
+                                    "Flink will perform broadcast hash join optimization when the runtime "
+                                            + "statistics on one side of a join operator is less than the "
+                                            + "threshold `table.optimizer.join.broadcast-threshold`. The "
+                                            + "value of this configuration option decides when Flink should "
+                                            + "perform this optimization. AUTO means Flink will automatically "
+                                            + "choose the timing for optimization, RUNTIME_ONLY means broadcast "
+                                            + "hash join optimization is only performed at runtime, and NONE "
+                                            + "means the optimization is only carried out at compile time.");
+
     /**
      * The data volume of build side needs to be under this value. If the data volume of build side
      * is too large, the building overhead will be too large, which may lead to a negative impact on
@@ -304,4 +323,33 @@ public enum NonDeterministicUpdateStrategy {
          */
         IGNORE
     }
+
+    /** Strategies used for {@link #TABLE_OPTIMIZER_ADAPTIVE_BROADCAST_JOIN_STRATEGY}. */
+    @PublicEvolving
+    public enum AdaptiveBroadcastJoinStrategy implements DescribedEnum {
+        AUTO("auto", text("Flink will automatically choose the timing for optimization")),
+        RUNTIME_ONLY(
+                "runtime_only",
+                text("Broadcast hash join optimization is only performed at runtime.")),
+        NONE("none", text("Broadcast hash join optimization is only carried out at compile time."));
+
+        private final String value;
+
+        private final InlineElement description;
+
+        AdaptiveBroadcastJoinStrategy(String value, InlineElement description) {
+            this.value = value;
+            this.description = description;
+        }
+
+        @Override
+        public String toString() {
+            return value;
+        }
+
+        @Override
+        public InlineElement getDescription() {
+            return description;
+        }
+    }
 }
diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/AdaptiveJoinExecNode.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/AdaptiveJoinExecNode.java
new file mode 100644
--- /dev/null
+++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/AdaptiveJoinExecNode.java
@@ -0,0 +1,31 @@
+/*
+ * 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.planner.plan.nodes.exec;
+
+import org.apache.flink.table.planner.plan.nodes.exec.batch.BatchExecAdaptiveJoin;
+
+/** A {@link ExecNode} which support to convert to adaptive join node. */
+public interface AdaptiveJoinExecNode {
+
+    /** Check whether the join node can be transformed to {@link BatchExecAdaptiveJoin}. */
+    boolean canBeTransformedToAdaptiveJoin();
+
+    /** Transform this node to {@link BatchExecAdaptiveJoin}. */
+    BatchExecAdaptiveJoin toAdaptiveJoinNode();
+}
diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/batch/BatchExecAdaptiveJoin.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/batch/BatchExecAdaptiveJoin.java
new file mode 100644
--- /dev/null
+++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/batch/BatchExecAdaptiveJoin.java
@@ -0,0 +1,166 @@
+/*
+ * 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.planner.plan.nodes.exec.batch;
+
+import org.apache.flink.api.dag.Transformation;
+import org.apache.flink.configuration.ReadableConfig;
+import org.apache.flink.streaming.api.operators.StreamOperatorFactory;
+import org.apache.flink.table.api.TableException;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.planner.adaptive.AdaptiveJoinOperatorGenerator;
+import org.apache.flink.table.planner.delegation.PlannerBase;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecEdge;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeBase;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeConfig;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeContext;
+import org.apache.flink.table.planner.plan.nodes.exec.InputProperty;
+import org.apache.flink.table.planner.plan.nodes.exec.SingleTransformationTranslator;
+import org.apache.flink.table.planner.plan.nodes.exec.spec.JoinSpec;
+import org.apache.flink.table.planner.plan.nodes.exec.utils.ExecNodeUtil;
+import org.apache.flink.table.planner.plan.utils.JoinUtil;
+import org.apache.flink.table.planner.plan.utils.OperatorType;
+import org.apache.flink.table.runtime.generated.GeneratedJoinCondition;
+import org.apache.flink.table.runtime.operators.join.adaptive.AdaptiveJoin;
+import org.apache.flink.table.runtime.operators.join.adaptive.AdaptiveJoinOperatorFactory;
+import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.util.InstantiationUtil;
+
+import java.io.IOException;
+import java.util.List;
+
+/** {@link BatchExecNode} for adaptive join. */
+public class BatchExecAdaptiveJoin extends ExecNodeBase<RowData>
+        implements BatchExecNode<RowData>, SingleTransformationTranslator<RowData> {
+
+    private final JoinSpec joinSpec;
+    private final boolean leftIsBuild;
+    private final int estimatedLeftAvgRowSize;
+    private final int estimatedRightAvgRowSize;
+    private final long estimatedLeftRowCount;
+    private final long estimatedRightRowCount;
+    private final boolean tryDistinctBuildRow;
+    private final String description;
+    private final OperatorType originalJoin;
+
+    public BatchExecAdaptiveJoin(
+            ReadableConfig tableConfig,
+            JoinSpec joinSpec,
+            int estimatedLeftAvgRowSize,
+            int estimatedRightAvgRowSize,
+            long estimatedLeftRowCount,
+            long estimatedRightRowCount,
+            boolean leftIsBuild,
+            boolean tryDistinctBuildRow,
+            List<InputProperty> inputProperties,
+            RowType outputType,
+            String description,
+            OperatorType originalJoin) {
+        super(
+                ExecNodeContext.newNodeId(),
+                ExecNodeContext.newContext(BatchExecAdaptiveJoin.class),
+                ExecNodeContext.newPersistedConfig(BatchExecAdaptiveJoin.class, tableConfig),
+                inputProperties,
+                outputType,
+                description);
+        this.joinSpec = joinSpec;
+        this.estimatedLeftAvgRowSize = estimatedLeftAvgRowSize;
+        this.estimatedRightAvgRowSize = estimatedRightAvgRowSize;
+        this.estimatedLeftRowCount = estimatedLeftRowCount;
+        this.estimatedRightRowCount = estimatedRightRowCount;
+        this.leftIsBuild = leftIsBuild;
+        this.tryDistinctBuildRow = tryDistinctBuildRow;
+        this.description = description;
+        this.originalJoin = originalJoin;
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    protected Transformation<RowData> translateToPlanInternal(
+            PlannerBase planner, ExecNodeConfig config) {
+        ExecEdge leftInputEdge = getInputEdges().get(0);
+        ExecEdge rightInputEdge = getInputEdges().get(1);
+
+        Transformation<RowData> leftInputTransform =
+                (Transformation<RowData>) leftInputEdge.translateToPlan(planner);
+        Transformation<RowData> rightInputTransform =
+                (Transformation<RowData>) rightInputEdge.translateToPlan(planner);
+        // get input types
+        RowType leftType = (RowType) leftInputEdge.getOutputType();
+        RowType rightType = (RowType) rightInputEdge.getOutputType();
+        long managedMemory = JoinUtil.getManagedMemory(joinSpec.getJoinType(), config);
+        GeneratedJoinCondition condFunc =
+                JoinUtil.generateConditionFunction(
+                        config,
+                        planner.getFlinkContext().getClassLoader(),
+                        joinSpec.getNonEquiCondition().orElse(null),
+                        leftType,
+                        rightType);
+
+        AdaptiveJoinOperatorGenerator adaptiveJoin =
+                new AdaptiveJoinOperatorGenerator(
+                        joinSpec.getLeftKeys(),
+                        joinSpec.getRightKeys(),
+                        joinSpec.getJoinType(),
+                        joinSpec.getFilterNulls(),
+                        leftType,
+                        rightType,
+                        condFunc,
+                        estimatedLeftAvgRowSize,
+                        estimatedRightAvgRowSize,
+                        estimatedLeftRowCount,
+                        estimatedRightRowCount,
+                        tryDistinctBuildRow,
+                        managedMemory,
+                        leftIsBuild,
+                        originalJoin);
+
+        return ExecNodeUtil.createTwoInputTransformation(
+                leftInputTransform,
+                rightInputTransform,
+                createTransformationName(config),
+                createTransformationDescription(config),
+                getAdaptiveJoinOperatorFactory(adaptiveJoin),
+                InternalTypeInfo.of(getOutputType()),
+                // Given that the probe side might be decided at runtime, we choose the larger
+                // parallelism here.
+                Math.max(leftInputTransform.getParallelism(), rightInputTransform.getParallelism()),
+                managedMemory,
+                false);
+    }
+
+    private StreamOperatorFactory<RowData> getAdaptiveJoinOperatorFactory(
+            AdaptiveJoin adaptiveJoin) {
+        try {
+            byte[] adaptiveJoinSerialized = InstantiationUtil.serializeObject(adaptiveJoin);
+            return new AdaptiveJoinOperatorFactory<>(adaptiveJoinSerialized);
+        } catch (IOException e) {
+            throw new TableException("The adaptive join operator failed to serialize.", e);
+        }
+    }
+
+    @Override
+    public String getDescription() {
+        return "AdaptiveJoin("
+                + "originalJoin=["
+                + originalJoin
+                + "], "
+                + description.substring(description.indexOf('(') + 1);
+    }
+}
diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/batch/BatchExecHashJoin.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/batch/BatchExecHashJoin.java
--- a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/batch/BatchExecHashJoin.java
+++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/batch/BatchExecHashJoin.java
@@ -21,17 +21,16 @@
 import org.apache.flink.FlinkVersion;
 import org.apache.flink.api.dag.Transformation;
 import org.apache.flink.configuration.ReadableConfig;
-import org.apache.flink.streaming.api.operators.SimpleOperatorFactory;
 import org.apache.flink.streaming.api.operators.StreamOperatorFactory;
 import org.apache.flink.table.api.config.ExecutionConfigOptions;
 import org.apache.flink.table.data.RowData;
 import org.apache.flink.table.planner.codegen.CodeGeneratorContext;
 import org.apache.flink.table.planner.codegen.LongHashJoinGenerator;
-import org.apache.flink.table.planner.codegen.ProjectionCodeGenerator;
 import org.apache.flink.table.planner.delegation.PlannerBase;
 import org.apache.flink.table.planner.plan.fusion.OpFusionCodegenSpecGenerator;
 import org.apache.flink.table.planner.plan.fusion.generator.TwoInputOpFusionCodegenSpecGenerator;
 import org.apache.flink.table.planner.plan.fusion.spec.HashJoinFusionCodegenSpec;
+import org.apache.flink.table.planner.plan.nodes.exec.AdaptiveJoinExecNode;
 import org.apache.flink.table.planner.plan.nodes.exec.ExecEdge;
 import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeBase;
 import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeConfig;
@@ -41,14 +40,12 @@
 import org.apache.flink.table.planner.plan.nodes.exec.SingleTransformationTranslator;
 import org.apache.flink.table.planner.plan.nodes.exec.spec.JoinSpec;
 import org.apache.flink.table.planner.plan.nodes.exec.utils.ExecNodeUtil;
+import org.apache.flink.table.planner.plan.utils.HashJoinOperatorUtil;
 import org.apache.flink.table.planner.plan.utils.JoinUtil;
-import org.apache.flink.table.planner.plan.utils.SorMergeJoinOperatorUtil;
+import org.apache.flink.table.planner.plan.utils.OperatorType;
 import org.apache.flink.table.runtime.generated.GeneratedJoinCondition;
-import org.apache.flink.table.runtime.generated.GeneratedProjection;
 import org.apache.flink.table.runtime.operators.join.FlinkJoinType;
-import org.apache.flink.table.runtime.operators.join.HashJoinOperator;
 import org.apache.flink.table.runtime.operators.join.HashJoinType;
-import org.apache.flink.table.runtime.operators.join.SortMergeJoinFunction;
 import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
 import org.apache.flink.table.types.logical.LogicalType;
 import org.apache.flink.table.types.logical.RowType;
@@ -78,7 +75,9 @@
         minPlanVersion = FlinkVersion.v2_0,
         minStateVersion = FlinkVersion.v2_0)
 public class BatchExecHashJoin extends ExecNodeBase<RowData>
-        implements BatchExecNode<RowData>, SingleTransformationTranslator<RowData> {
+        implements BatchExecNode<RowData>,
+                SingleTransformationTranslator<RowData>,
+                AdaptiveJoinExecNode {
 
     public static final String JOIN_TRANSFORMATION = "join";
     public static final String FIELD_NAME_JOIN_SPEC = "joinSpec";
@@ -89,6 +88,7 @@ public class BatchExecHashJoin extends ExecNodeBase<RowData>
     public static final String FIELD_NAME_ESTIMATED_LEFT_ROW_COUNT = "estimatedLeftRowCount";
     public static final String FIELD_NAME_ESTIMATED_RIGHT_ROW_COUNT = "estimatedRightRowCount";
     public static final String FIELD_NAME_TRY_DISTINCT_BUILD_ROW = "tryDistinctBuildRow";
+    public static final String FIELD_NAME_WITH_JOIN_STRATEGY_HINT = "withJobStrategyHint";
 
     @JsonProperty(FIELD_NAME_JOIN_SPEC)
     private final JoinSpec joinSpec;
@@ -111,6 +111,9 @@ public class BatchExecHashJoin extends ExecNodeBase<RowData>
     @JsonProperty(FIELD_NAME_ESTIMATED_RIGHT_ROW_COUNT)
     private final long estimatedRightRowCount;
 
+    @JsonProperty(FIELD_NAME_WITH_JOIN_STRATEGY_HINT)
+    private final boolean withJobStrategyHint;
+
     @JsonProperty(FIELD_NAME_TRY_DISTINCT_BUILD_ROW)
     private final boolean tryDistinctBuildRow;
 
@@ -127,6 +130,7 @@ public BatchExecHashJoin(
             InputProperty leftInputProperty,
             InputProperty rightInputProperty,
             RowType outputType,
+            boolean withJobStrategyHint,
             String description) {
         super(
                 ExecNodeContext.newNodeId(),
@@ -143,6 +147,7 @@ public BatchExecHashJoin(
         this.estimatedLeftRowCount = estimatedLeftRowCount;
         this.estimatedRightRowCount = estimatedRightRowCount;
         this.tryDistinctBuildRow = tryDistinctBuildRow;
+        this.withJobStrategyHint = withJobStrategyHint;
     }
 
     @JsonCreator
@@ -160,7 +165,8 @@ public BatchExecHashJoin(
             @JsonProperty(FIELD_NAME_TRY_DISTINCT_BUILD_ROW) boolean tryDistinctBuildRow,
             @JsonProperty(FIELD_NAME_INPUT_PROPERTIES) List<InputProperty> inputProperties,
             @JsonProperty(FIELD_NAME_OUTPUT_TYPE) RowType outputType,
-            @JsonProperty(FIELD_NAME_DESCRIPTION) String description) {
+            @JsonProperty(FIELD_NAME_DESCRIPTION) String description,
+            @JsonProperty(FIELD_NAME_WITH_JOIN_STRATEGY_HINT) boolean withJobStrategyHint) {
         super(id, context, persistedConfig, inputProperties, outputType, description);
         checkArgument(inputProperties.size() == 2);
         this.joinSpec = checkNotNull(joinSpec);
@@ -171,6 +177,7 @@ public BatchExecHashJoin(
         this.estimatedLeftRowCount = estimatedLeftRowCount;
         this.estimatedRightRowCount = estimatedRightRowCount;
         this.tryDistinctBuildRow = tryDistinctBuildRow;
+        this.withJobStrategyHint = withJobStrategyHint;
     }
 
     @Override
@@ -187,14 +194,7 @@ protected Transformation<RowData> translateToPlanInternal(
         // get input types
         RowType leftType = (RowType) leftInputEdge.getOutputType();
         RowType rightType = (RowType) rightInputEdge.getOutputType();
-
-        JoinUtil.validateJoinSpec(joinSpec, leftType, rightType, false);
-
-        int[] leftKeys = joinSpec.getLeftKeys();
-        int[] rightKeys = joinSpec.getRightKeys();
-        LogicalType[] keyFieldTypes =
-                IntStream.of(leftKeys).mapToObj(leftType::getTypeAt).toArray(LogicalType[]::new);
-        RowType keyType = RowType.of(keyFieldTypes);
+        long managedMemory = JoinUtil.getManagedMemory(joinSpec.getJoinType(), config);
 
         GeneratedJoinCondition condFunc =
                 JoinUtil.generateConditionFunction(
@@ -204,140 +204,33 @@ protected Transformation<RowData> translateToPlanInternal(
                         leftType,
                         rightType);
 
-        // projection for equals
-        GeneratedProjection leftProj =
-                ProjectionCodeGenerator.generateProjection(
-                        new CodeGeneratorContext(
-                                config, planner.getFlinkContext().getClassLoader()),
-                        "HashJoinLeftProjection",
+        StreamOperatorFactory<RowData> operator =
+                HashJoinOperatorUtil.generateOperatorFactory(
+                        joinSpec.getLeftKeys(),
+                        joinSpec.getRightKeys(),
+                        joinSpec.getJoinType(),
+                        joinSpec.getFilterNulls(),
                         leftType,
-                        keyType,
-                        leftKeys);
-        GeneratedProjection rightProj =
-                ProjectionCodeGenerator.generateProjection(
-                        new CodeGeneratorContext(
-                                config, planner.getFlinkContext().getClassLoader()),
-                        "HashJoinRightProjection",
                         rightType,
-                        keyType,
-                        rightKeys);
+                        condFunc,
+                        leftIsBuild,
+                        estimatedLeftAvgRowSize,
+                        estimatedRightAvgRowSize,
+                        estimatedLeftRowCount,
+                        estimatedRightRowCount,
+                        tryDistinctBuildRow,
+                        managedMemory,
+                        config,
+                        planner.getFlinkContext().getClassLoader());
 
         Transformation<RowData> buildTransform;
         Transformation<RowData> probeTransform;
-        GeneratedProjection buildProj;
-        GeneratedProjection probeProj;
-        int[] buildKeys;
-        int[] probeKeys;
-        RowType buildType;
-        RowType probeType;
-        int buildRowSize;
-        long buildRowCount;
-        long probeRowCount;
-        boolean reverseJoin = !leftIsBuild;
         if (leftIsBuild) {
             buildTransform = leftInputTransform;
-            buildProj = leftProj;
-            buildType = leftType;
-            buildRowSize = estimatedLeftAvgRowSize;
-            buildRowCount = estimatedLeftRowCount;
-            buildKeys = leftKeys;
-
             probeTransform = rightInputTransform;
-            probeProj = rightProj;
-            probeType = rightType;
-            probeRowCount = estimatedRightRowCount;
-            probeKeys = rightKeys;
         } else {
             buildTransform = rightInputTransform;
-            buildProj = rightProj;
-            buildType = rightType;
-            buildRowSize = estimatedRightAvgRowSize;
-            buildRowCount = estimatedRightRowCount;
-            buildKeys = rightKeys;
-
             probeTransform = leftInputTransform;
-            probeProj = leftProj;
-            probeType = leftType;
-            probeRowCount = estimatedLeftRowCount;
-            probeKeys = leftKeys;
-        }
-
-        // operator
-        StreamOperatorFactory<RowData> operator;
-        FlinkJoinType joinType = joinSpec.getJoinType();
-        HashJoinType hashJoinType =
-                HashJoinType.of(
-                        leftIsBuild,
-                        joinType.isLeftOuter(),
-                        joinType.isRightOuter(),
-                        joinType == FlinkJoinType.SEMI,
-                        joinType == FlinkJoinType.ANTI);
-
-        long externalBufferMemory =
-                config.get(ExecutionConfigOptions.TABLE_EXEC_RESOURCE_EXTERNAL_BUFFER_MEMORY)
-                        .getBytes();
-        long managedMemory = getLargeManagedMemory(joinType, config);
-
-        // sort merge join function
-        SortMergeJoinFunction sortMergeJoinFunction =
-                SorMergeJoinOperatorUtil.getSortMergeJoinFunction(
-                        planner.getFlinkContext().getClassLoader(),
-                        config,
-                        joinType,
-                        leftType,
-                        rightType,
-                        leftKeys,
-                        rightKeys,
-                        keyType,
-                        leftIsBuild,
-                        joinSpec.getFilterNulls(),
-                        condFunc,
-                        1.0 * externalBufferMemory / managedMemory);
-
-        boolean compressionEnabled =
-                config.get(ExecutionConfigOptions.TABLE_EXEC_SPILL_COMPRESSION_ENABLED);
-        int compressionBlockSize =
-                (int)
-                        config.get(ExecutionConfigOptions.TABLE_EXEC_SPILL_COMPRESSION_BLOCK_SIZE)
-                                .getBytes();
-        if (LongHashJoinGenerator.support(hashJoinType, keyType, joinSpec.getFilterNulls())) {
-            operator =
-                    LongHashJoinGenerator.gen(
-                            config,
-                            planner.getFlinkContext().getClassLoader(),
-                            hashJoinType,
-                            keyType,
-                            buildType,
-                            probeType,
-                            buildKeys,
-                            probeKeys,
-                            buildRowSize,
-                            buildRowCount,
-                            reverseJoin,
-                            condFunc,
-                            leftIsBuild,
-                            compressionEnabled,
-                            compressionBlockSize,
-                            sortMergeJoinFunction);
-        } else {
-            operator =
-                    SimpleOperatorFactory.of(
-                            HashJoinOperator.newHashJoinOperator(
-                                    hashJoinType,
-                                    leftIsBuild,
-                                    compressionEnabled,
-                                    compressionBlockSize,
-                                    condFunc,
-                                    reverseJoin,
-                                    joinSpec.getFilterNulls(),
-                                    buildProj,
-                                    probeProj,
-                                    tryDistinctBuildRow,
-                                    buildRowSize,
-                                    buildRowCount,
-                                    probeRowCount,
-                                    keyType,
-                                    sortMergeJoinFunction));
         }
 
         return ExecNodeUtil.createTwoInputTransformation(
@@ -351,29 +244,6 @@ protected Transformation<RowData> translateToPlanInternal(
                 false);
     }
 
-    private long getLargeManagedMemory(FlinkJoinType joinType, ExecNodeConfig config) {
-        long hashJoinManagedMemory =
-                config.get(ExecutionConfigOptions.TABLE_EXEC_RESOURCE_HASH_JOIN_MEMORY).getBytes();
-
-        // The memory used by SortMergeJoinIterator that buffer the matched rows, each side needs
-        // this memory if it is full outer join
-        long externalBufferMemory =
-                config.get(ExecutionConfigOptions.TABLE_EXEC_RESOURCE_EXTERNAL_BUFFER_MEMORY)
-                        .getBytes();
-        // The memory used by BinaryExternalSorter for sort, the left and right side both need it
-        long sortMemory =
-                config.get(ExecutionConfigOptions.TABLE_EXEC_RESOURCE_SORT_MEMORY).getBytes();
-        int externalBufferNum = 1;
-        if (joinType == FlinkJoinType.FULL) {
-            externalBufferNum = 2;
-        }
-        long sortMergeJoinManagedMemory = externalBufferMemory * externalBufferNum + sortMemory * 2;
-
-        // Due to hash join maybe fallback to sort merge join, so here managed memory choose the
-        // large one
-        return Math.max(hashJoinManagedMemory, sortMergeJoinManagedMemory);
-    }
-
     @Override
     public boolean supportFusionCodegen() {
         RowType leftType = (RowType) getInputEdges().get(0).getOutputType();
@@ -407,7 +277,7 @@ protected OpFusionCodegenSpecGenerator translateToFusionCodegenSpecInternal(
                 (int)
                         config.get(ExecutionConfigOptions.TABLE_EXEC_SPILL_COMPRESSION_BLOCK_SIZE)
                                 .getBytes();
-        long managedMemory = getLargeManagedMemory(joinSpec.getJoinType(), config);
+        long managedMemory = JoinUtil.getManagedMemory(joinSpec.getJoinType(), config);
         OpFusionCodegenSpecGenerator hashJoinGenerator =
                 new TwoInputOpFusionCodegenSpecGenerator(
                         leftInput,
@@ -432,4 +302,26 @@ protected OpFusionCodegenSpecGenerator translateToFusionCodegenSpecInternal(
         rightInput.addOutput(2, hashJoinGenerator);
         return hashJoinGenerator;
     }
+
+    @Override
+    public boolean canBeTransformedToAdaptiveJoin() {
+        return !withJobStrategyHint && joinSpec.getJoinType() != FlinkJoinType.FULL;
+    }
+
+    @Override
+    public BatchExecAdaptiveJoin toAdaptiveJoinNode() {
+        return new BatchExecAdaptiveJoin(
+                getPersistedConfig(),
+                joinSpec,
+                estimatedLeftAvgRowSize,
+                estimatedRightAvgRowSize,
+                estimatedLeftRowCount,
+                estimatedRightRowCount,
+                leftIsBuild,
+                tryDistinctBuildRow,
+                getInputProperties(),
+                (RowType) getOutputType(),
+                getDescription(),
+                OperatorType.ShuffleHashJoin);
+    }
 }
diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/batch/BatchExecSortMergeJoin.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/batch/BatchExecSortMergeJoin.java
--- a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/batch/BatchExecSortMergeJoin.java
+++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/batch/BatchExecSortMergeJoin.java
@@ -20,47 +20,53 @@
 
 import org.apache.flink.api.dag.Transformation;
 import org.apache.flink.configuration.ReadableConfig;
-import org.apache.flink.streaming.api.operators.SimpleOperatorFactory;
+import org.apache.flink.streaming.api.operators.StreamOperatorFactory;
 import org.apache.flink.table.api.config.ExecutionConfigOptions;
 import org.apache.flink.table.data.RowData;
 import org.apache.flink.table.planner.delegation.PlannerBase;
+import org.apache.flink.table.planner.plan.nodes.exec.AdaptiveJoinExecNode;
 import org.apache.flink.table.planner.plan.nodes.exec.ExecEdge;
 import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeBase;
 import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeConfig;
 import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeContext;
 import org.apache.flink.table.planner.plan.nodes.exec.InputProperty;
 import org.apache.flink.table.planner.plan.nodes.exec.SingleTransformationTranslator;
+import org.apache.flink.table.planner.plan.nodes.exec.spec.JoinSpec;
 import org.apache.flink.table.planner.plan.nodes.exec.utils.ExecNodeUtil;
 import org.apache.flink.table.planner.plan.utils.JoinUtil;
+import org.apache.flink.table.planner.plan.utils.OperatorType;
 import org.apache.flink.table.planner.plan.utils.SorMergeJoinOperatorUtil;
 import org.apache.flink.table.runtime.generated.GeneratedJoinCondition;
 import org.apache.flink.table.runtime.operators.join.FlinkJoinType;
-import org.apache.flink.table.runtime.operators.join.SortMergeJoinFunction;
-import org.apache.flink.table.runtime.operators.join.SortMergeJoinOperator;
 import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
-import org.apache.flink.table.types.logical.LogicalType;
 import org.apache.flink.table.types.logical.RowType;
 
 import org.apache.calcite.rex.RexNode;
 
 import javax.annotation.Nullable;
 
 import java.util.Arrays;
-import java.util.stream.IntStream;
 
 import static org.apache.flink.util.Preconditions.checkArgument;
 import static org.apache.flink.util.Preconditions.checkNotNull;
 
 /** {@link BatchExecNode} for Sort Merge Join. */
 public class BatchExecSortMergeJoin extends ExecNodeBase<RowData>
-        implements BatchExecNode<RowData>, SingleTransformationTranslator<RowData> {
+        implements BatchExecNode<RowData>,
+                SingleTransformationTranslator<RowData>,
+                AdaptiveJoinExecNode {
 
     private final FlinkJoinType joinType;
     private final int[] leftKeys;
     private final int[] rightKeys;
     private final boolean[] filterNulls;
     private final @Nullable RexNode nonEquiCondition;
+    private final int estimatedLeftAvgRowSize;
+    private final int estimatedRightAvgRowSize;
+    private final long estimatedLeftRowCount;
+    private final long estimatedRightRowCount;
     private final boolean leftIsSmaller;
+    private final boolean withJobStrategyHint;
 
     public BatchExecSortMergeJoin(
             ReadableConfig tableConfig,
@@ -69,10 +75,15 @@ public BatchExecSortMergeJoin(
             int[] rightKeys,
             boolean[] filterNulls,
             @Nullable RexNode nonEquiCondition,
+            int estimatedLeftAvgRowSize,
+            int estimatedRightAvgRowSize,
+            long estimatedLeftRowCount,
+            long estimatedRightRowCount,
             boolean leftIsSmaller,
             InputProperty leftInputProperty,
             InputProperty rightInputProperty,
             RowType outputType,
+            boolean withJobStrategyHint,
             String description) {
         super(
                 ExecNodeContext.newNodeId(),
@@ -89,7 +100,12 @@ public BatchExecSortMergeJoin(
         checkArgument(leftKeys.length == filterNulls.length);
 
         this.nonEquiCondition = nonEquiCondition;
+        this.estimatedLeftAvgRowSize = estimatedLeftAvgRowSize;
+        this.estimatedRightAvgRowSize = estimatedRightAvgRowSize;
+        this.estimatedLeftRowCount = estimatedLeftRowCount;
+        this.estimatedRightRowCount = estimatedRightRowCount;
         this.leftIsSmaller = leftIsSmaller;
+        this.withJobStrategyHint = withJobStrategyHint;
     }
 
     @Override
@@ -103,18 +119,6 @@ protected Transformation<RowData> translateToPlanInternal(
         RowType leftType = (RowType) leftInputEdge.getOutputType();
         RowType rightType = (RowType) rightInputEdge.getOutputType();
 
-        LogicalType[] keyFieldTypes =
-                IntStream.of(leftKeys).mapToObj(leftType::getTypeAt).toArray(LogicalType[]::new);
-        RowType keyType = RowType.of(keyFieldTypes);
-
-        GeneratedJoinCondition condFunc =
-                JoinUtil.generateConditionFunction(
-                        config,
-                        planner.getFlinkContext().getClassLoader(),
-                        nonEquiCondition,
-                        leftType,
-                        rightType);
-
         long externalBufferMemory =
                 config.get(ExecutionConfigOptions.TABLE_EXEC_RESOURCE_EXTERNAL_BUFFER_MEMORY)
                         .getBytes();
@@ -127,20 +131,27 @@ protected Transformation<RowData> translateToPlanInternal(
 
         long managedMemory = externalBufferMemory * externalBufferNum + sortMemory * 2;
 
-        SortMergeJoinFunction sortMergeJoinFunction =
-                SorMergeJoinOperatorUtil.getSortMergeJoinFunction(
-                        planner.getFlinkContext().getClassLoader(),
+        GeneratedJoinCondition condFunc =
+                JoinUtil.generateConditionFunction(
                         config,
-                        joinType,
+                        planner.getFlinkContext().getClassLoader(),
+                        nonEquiCondition,
+                        leftType,
+                        rightType);
+
+        StreamOperatorFactory<RowData> sortMergeJoinOperatorFactory =
+                SorMergeJoinOperatorUtil.generateOperatorFactory(
+                        condFunc,
                         leftType,
                         rightType,
                         leftKeys,
                         rightKeys,
-                        keyType,
+                        joinType,
+                        config,
                         leftIsSmaller,
                         filterNulls,
-                        condFunc,
-                        1.0 * externalBufferMemory / managedMemory);
+                        managedMemory,
+                        planner.getFlinkContext().getClassLoader());
 
         Transformation<RowData> leftInputTransform =
                 (Transformation<RowData>) leftInputEdge.translateToPlan(planner);
@@ -151,10 +162,32 @@ protected Transformation<RowData> translateToPlanInternal(
                 rightInputTransform,
                 createTransformationName(config),
                 createTransformationDescription(config),
-                SimpleOperatorFactory.of(new SortMergeJoinOperator(sortMergeJoinFunction)),
+                sortMergeJoinOperatorFactory,
                 InternalTypeInfo.of(getOutputType()),
                 rightInputTransform.getParallelism(),
                 managedMemory,
                 false);
     }
+
+    @Override
+    public boolean canBeTransformedToAdaptiveJoin() {
+        return !withJobStrategyHint && joinType != FlinkJoinType.FULL;
+    }
+
+    @Override
+    public BatchExecAdaptiveJoin toAdaptiveJoinNode() {
+        return new BatchExecAdaptiveJoin(
+                getPersistedConfig(),
+                new JoinSpec(joinType, leftKeys, rightKeys, filterNulls, nonEquiCondition),
+                estimatedLeftAvgRowSize,
+                estimatedRightAvgRowSize,
+                estimatedLeftRowCount,
+                estimatedRightRowCount,
+                leftIsSmaller,
+                false,
+                getInputProperties(),
+                (RowType) getOutputType(),
+                getDescription(),
+                OperatorType.SortMergeJoin);
+    }
 }
diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/processor/AdaptiveJoinProcessor.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/processor/AdaptiveJoinProcessor.java
new file mode 100644
--- /dev/null
+++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/processor/AdaptiveJoinProcessor.java
@@ -0,0 +1,179 @@
+/*
+ * 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.planner.plan.nodes.exec.processor;
+
+import org.apache.flink.configuration.JobManagerOptions;
+import org.apache.flink.table.api.TableConfig;
+import org.apache.flink.table.api.TableException;
+import org.apache.flink.table.api.config.OptimizerConfigOptions;
+import org.apache.flink.table.planner.plan.nodes.exec.AdaptiveJoinExecNode;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecEdge;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNode;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeGraph;
+import org.apache.flink.table.planner.plan.nodes.exec.InputProperty;
+import org.apache.flink.table.planner.plan.nodes.exec.InputProperty.DistributionType;
+import org.apache.flink.table.planner.plan.nodes.exec.batch.BatchExecAdaptiveJoin;
+import org.apache.flink.table.planner.plan.nodes.exec.batch.BatchExecExchange;
+import org.apache.flink.table.planner.plan.nodes.exec.stream.StreamExecNode;
+import org.apache.flink.table.planner.plan.nodes.exec.visitor.AbstractExecNodeExactlyOnceVisitor;
+import org.apache.flink.table.planner.plan.utils.OperatorType;
+import org.apache.flink.table.planner.utils.TableConfigUtils;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static org.apache.flink.table.planner.plan.nodes.exec.InputProperty.DistributionType.KEEP_INPUT_AS_IS;
+
+/**
+ * A {@link ExecNodeGraphProcessor} which replace the qualified join nodes into adaptive join nodes.
+ */
+public class AdaptiveJoinProcessor implements ExecNodeGraphProcessor {
+
+    @Override
+    public ExecNodeGraph process(ExecNodeGraph execGraph, ProcessorContext context) {
+        if (execGraph.getRootNodes().get(0) instanceof StreamExecNode) {
+            throw new TableException("AdaptiveJoin does not support streaming jobs.");
+        }
+        if (!isAdaptiveJoinEnabled(context)) {
+            return execGraph;
+        }
+
+        AbstractExecNodeExactlyOnceVisitor visitor =
+                new AbstractExecNodeExactlyOnceVisitor() {
+                    @Override
+                    protected void visitNode(ExecNode<?> node) {
+                        visitInputs(node);
+                        // AdaptiveJoin conversion should be avoided when there is a
+                        // KEEP_INPUT_AS_IS constraint downstream. And we don't need to check all
+                        // downstream nodes of the join, because the KEEP_INPUT_AS_IS constraint
+                        // will be bound to BatchExecExchange, which will be the direct downstream
+                        // node of the join.
+                        if (shouldKeepInputAsIs(node.getInputProperties())) {
+                            return;
+                        }
+                        for (int i = 0; i < node.getInputEdges().size(); ++i) {
+                            ExecEdge edge = node.getInputEdges().get(i);
+                            ExecNode<?> newNode = tryReplaceWithAdaptiveJoinNode(edge.getSource());
+                            node.replaceInputEdge(
+                                    i,
+                                    ExecEdge.builder()
+                                            .source(newNode)
+                                            .target(node)
+                                            .shuffle(edge.getShuffle())
+                                            .exchangeMode(edge.getExchangeMode())
+                                            .build());
+                        }
+                    }
+                };
+
+        List<ExecNode<?>> newRootNodes =
+                execGraph.getRootNodes().stream()
+                        .map(
+                                node -> {
+                                    node = tryReplaceWithAdaptiveJoinNode(node);
+                                    node.accept(visitor);
+                                    return node;
+                                })
+                        .collect(Collectors.toList());
+
+        return new ExecNodeGraph(execGraph.getFlinkVersion(), newRootNodes);
+    }
+
+    private ExecNode<?> tryReplaceWithAdaptiveJoinNode(ExecNode<?> node) {
+        // For AdaptiveJoin to be converted, its upstream input must ensure:
+        // 1. Data distribution is by Hash.
+        // 2. No upstream nodes require KEEP_INPUT_AS_IS (achieved by inserting BatchExecExchange).
+        if (!(areAllInputsHashShuffle(node))
+                || shouldKeepUpstreamExchangeInputAsIs(node.getInputEdges())) {
+            return node;
+        }
+        ExecNode<?> newNode = node;
+        if (node instanceof AdaptiveJoinExecNode
+                && ((AdaptiveJoinExecNode) node).canBeTransformedToAdaptiveJoin()) {
+            BatchExecAdaptiveJoin adaptiveJoin = ((AdaptiveJoinExecNode) node).toAdaptiveJoinNode();
+            replaceInputEdge(adaptiveJoin, node);
+            newNode = adaptiveJoin;
+        }
+
+        return newNode;
+    }
+
+    private boolean shouldKeepInputAsIs(List<InputProperty> inputProperties) {
+        return inputProperties.stream()
+                .anyMatch(
+                        inputProperty ->
+                                inputProperty.getRequiredDistribution().getType()
+                                        == KEEP_INPUT_AS_IS);
+    }
+
+    // If KEEP_INPUT_AS_IS constraint exists on an operator, it will always show on its upstream
+    // BatchExecExchange.
+    private boolean shouldKeepUpstreamExchangeInputAsIs(List<ExecEdge> inputEdges) {
+        return inputEdges.stream()
+                .filter(execEdge -> execEdge.getSource() instanceof BatchExecExchange)
+                .map(execEdge -> (BatchExecExchange) execEdge.getSource())
+                .anyMatch(exchange -> shouldKeepInputAsIs(exchange.getInputProperties()));
+    }
+
+    private boolean isAdaptiveJoinEnabled(ProcessorContext context) {
+        TableConfig tableConfig = context.getPlanner().getTableConfig();
+        boolean isAdaptiveJoinEnabled =
+                tableConfig.get(
+                                        OptimizerConfigOptions
+                                                .TABLE_OPTIMIZER_ADAPTIVE_BROADCAST_JOIN_STRATEGY)
+                                != OptimizerConfigOptions.AdaptiveBroadcastJoinStrategy.NONE
+                        && !TableConfigUtils.isOperatorDisabled(
+                                tableConfig, OperatorType.BroadcastHashJoin);
+        JobManagerOptions.SchedulerType schedulerType =
+                context.getPlanner()
+                        .getExecEnv()
+                        .getConfig()
+                        .getSchedulerType()
+                        .orElse(JobManagerOptions.SchedulerType.AdaptiveBatch);
+        boolean isAdaptiveBatchSchedulerEnabled =
+                schedulerType == JobManagerOptions.SchedulerType.AdaptiveBatch;
+
+        return isAdaptiveJoinEnabled && isAdaptiveBatchSchedulerEnabled;
+    }
+
+    private boolean areAllInputsHashShuffle(ExecNode<?> node) {
+        for (InputProperty inputProperty : node.getInputProperties()) {
+            if (inputProperty.getRequiredDistribution().getType() != DistributionType.HASH) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    private void replaceInputEdge(ExecNode<?> newNode, ExecNode<?> originalNode) {
+        List<ExecEdge> inputEdges = new ArrayList<>();
+        for (int i = 0; i < originalNode.getInputEdges().size(); ++i) {
+            ExecEdge edge = originalNode.getInputEdges().get(i);
+            inputEdges.add(
+                    ExecEdge.builder()
+                            .source(edge.getSource())
+                            .target(newNode)
+                            .shuffle(edge.getShuffle())
+                            .exchangeMode(edge.getExchangeMode())
+                            .build());
+        }
+        newNode.setInputEdges(inputEdges);
+    }
+}
diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/delegation/BatchPlanner.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/delegation/BatchPlanner.scala
--- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/delegation/BatchPlanner.scala
+++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/delegation/BatchPlanner.scala
@@ -25,11 +25,11 @@ import org.apache.flink.table.api.config.OptimizerConfigOptions
 import org.apache.flink.table.catalog.{CatalogManager, FunctionCatalog}
 import org.apache.flink.table.delegation.{Executor, InternalPlan}
 import org.apache.flink.table.module.ModuleManager
-import org.apache.flink.table.operations.{ModifyOperation, Operation}
+import org.apache.flink.table.operations.Operation
 import org.apache.flink.table.planner.plan.`trait`.FlinkRelDistributionTraitDef
 import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeGraph
 import org.apache.flink.table.planner.plan.nodes.exec.batch.BatchExecNode
-import org.apache.flink.table.planner.plan.nodes.exec.processor.{DeadlockBreakupProcessor, DynamicFilteringDependencyProcessor, ExecNodeGraphProcessor, ForwardHashExchangeProcessor, MultipleInputNodeCreationProcessor}
+import org.apache.flink.table.planner.plan.nodes.exec.processor.{AdaptiveJoinProcessor, DeadlockBreakupProcessor, DynamicFilteringDependencyProcessor, ExecNodeGraphProcessor, ForwardHashExchangeProcessor, MultipleInputNodeCreationProcessor}
 import org.apache.flink.table.planner.plan.nodes.exec.utils.ExecNodePlanDumper
 import org.apache.flink.table.planner.plan.optimize.{BatchCommonSubGraphBasedOptimizer, Optimizer}
 import org.apache.flink.table.planner.plan.utils.FlinkRelOptUtil
@@ -81,6 +81,7 @@ class BatchPlanner(
       processors.add(new MultipleInputNodeCreationProcessor(false))
     }
     processors.add(new ForwardHashExchangeProcessor)
+    processors.add(new AdaptiveJoinProcessor)
     processors
   }
 
diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/nodes/physical/batch/BatchPhysicalHashJoin.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/nodes/physical/batch/BatchPhysicalHashJoin.scala
--- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/nodes/physical/batch/BatchPhysicalHashJoin.scala
+++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/nodes/physical/batch/BatchPhysicalHashJoin.scala
@@ -49,7 +49,8 @@ class BatchPhysicalHashJoin(
     val leftIsBuild: Boolean,
     // true if build side is broadcast, else false
     val isBroadcast: Boolean,
-    val tryDistinctBuildRow: Boolean)
+    val tryDistinctBuildRow: Boolean,
+    val withJobStrategyHint: Boolean)
   extends BatchPhysicalJoinBase(cluster, traitSet, leftRel, rightRel, condition, joinType) {
 
   val hashJoinType: HashJoinType = HashJoinType.of(
@@ -75,7 +76,8 @@ class BatchPhysicalHashJoin(
       joinType,
       leftIsBuild,
       isBroadcast,
-      tryDistinctBuildRow)
+      tryDistinctBuildRow,
+      withJobStrategyHint)
   }
 
   override def explainTerms(pw: RelWriter): RelWriter = {
@@ -157,11 +159,8 @@ class BatchPhysicalHashJoin(
       FlinkTypeFactory.toLogicalRowType(left.getRowType),
       FlinkTypeFactory.toLogicalRowType(right.getRowType))
 
-    val mq = getCluster.getMetadataQuery
-    val leftRowSize = Util.first(mq.getAverageRowSize(left), 24).toInt
-    val leftRowCount = Util.first(mq.getRowCount(left), 200000).toLong
-    val rightRowSize = Util.first(mq.getAverageRowSize(right), 24).toInt
-    val rightRowCount = Util.first(mq.getRowCount(right), 200000).toLong
+    val (leftRowSize, leftRowCount, rightRowSize, rightRowCount) =
+      JoinUtil.getEstimatedRowStats(this)
     val (leftEdge, rightEdge) = getInputProperties
     new BatchExecHashJoin(
       unwrapTableConfig(this),
@@ -176,6 +175,7 @@ class BatchPhysicalHashJoin(
       leftEdge,
       rightEdge,
       FlinkTypeFactory.toLogicalRowType(getRowType),
+      withJobStrategyHint,
       getRelDetailedDescription)
   }
 
diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/nodes/physical/batch/BatchPhysicalSortMergeJoin.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/nodes/physical/batch/BatchPhysicalSortMergeJoin.scala
--- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/nodes/physical/batch/BatchPhysicalSortMergeJoin.scala
+++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/nodes/physical/batch/BatchPhysicalSortMergeJoin.scala
@@ -31,6 +31,7 @@ import org.apache.calcite.rel.{RelCollationTraitDef, RelNode, RelWriter}
 import org.apache.calcite.rel.core._
 import org.apache.calcite.rel.metadata.RelMetadataQuery
 import org.apache.calcite.rex.RexNode
+import org.apache.calcite.util.Util
 
 import scala.collection.JavaConversions._
 
@@ -45,7 +46,8 @@ class BatchPhysicalSortMergeJoin(
     // true if LHS is sorted by left join keys, else false
     val leftSorted: Boolean,
     // true if RHS is sorted by right join key, else false
-    val rightSorted: Boolean)
+    val rightSorted: Boolean,
+    withJobStrategyHint: Boolean)
   extends BatchPhysicalJoinBase(cluster, traitSet, leftRel, rightRel, condition, joinType) {
 
   protected def isMergeJoinSupportedType(joinRelType: FlinkJoinType): Boolean = {
@@ -70,7 +72,8 @@ class BatchPhysicalSortMergeJoin(
       conditionExpr,
       joinType,
       leftSorted,
-      rightSorted)
+      rightSorted,
+      withJobStrategyHint)
   }
 
   override def explainTerms(pw: RelWriter): RelWriter =
@@ -175,13 +178,19 @@ class BatchPhysicalSortMergeJoin(
       FlinkTypeFactory.toLogicalRowType(left.getRowType),
       FlinkTypeFactory.toLogicalRowType(right.getRowType))
 
+    val (leftRowSize, leftRowCount, rightRowSize, rightRowCount) =
+      JoinUtil.getEstimatedRowStats(this)
     new BatchExecSortMergeJoin(
       unwrapTableConfig(this),
       JoinTypeUtil.getFlinkJoinType(joinType),
       joinSpec.getLeftKeys,
       joinSpec.getRightKeys,
       joinSpec.getFilterNulls,
       condition,
+      leftRowSize,
+      rightRowSize,
+      leftRowCount,
+      rightRowCount,
       estimateOutputSize(getLeft) < estimateOutputSize(getRight),
       InputProperty
         .builder()
@@ -194,6 +203,7 @@ class BatchPhysicalSortMergeJoin(
         .damBehavior(InputProperty.DamBehavior.END_INPUT)
         .build(),
       FlinkTypeFactory.toLogicalRowType(getRowType),
+      withJobStrategyHint,
       getRelDetailedDescription)
   }
 
diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/batch/BatchPhysicalHashJoinRule.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/batch/BatchPhysicalHashJoinRule.scala
--- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/batch/BatchPhysicalHashJoinRule.scala
+++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/batch/BatchPhysicalHashJoinRule.scala
@@ -23,6 +23,7 @@ import org.apache.flink.table.planner.plan.`trait`.FlinkRelDistribution
 import org.apache.flink.table.planner.plan.nodes.FlinkConventions
 import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalJoin
 import org.apache.flink.table.planner.plan.nodes.physical.batch.BatchPhysicalHashJoin
+import org.apache.flink.table.planner.plan.utils.JoinUtil
 import org.apache.flink.table.planner.utils.ShortcutUtils.unwrapTableConfig
 
 import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall, RelTraitSet}
@@ -110,6 +111,7 @@ class BatchPhysicalHashJoinRule
       val newLeft = RelOptRule.convert(left, leftRequiredTrait)
       val newRight = RelOptRule.convert(right, rightRequiredTrait)
       val providedTraitSet = join.getTraitSet.replace(FlinkConventions.BATCH_PHYSICAL)
+      val withJobStrategyHint = JoinUtil.containsJoinStrategyHint(join.getHints)
 
       val newJoin = new BatchPhysicalHashJoin(
         join.getCluster,
@@ -120,7 +122,8 @@ class BatchPhysicalHashJoinRule
         join.getJoinType,
         isLeftToBroadcastOrBuild,
         isBroadcast,
-        tryDistinctBuildRow)
+        tryDistinctBuildRow,
+        withJobStrategyHint)
 
       call.transformTo(newJoin)
     }
diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/batch/BatchPhysicalJoinRuleBase.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/batch/BatchPhysicalJoinRuleBase.scala
--- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/batch/BatchPhysicalJoinRuleBase.scala
+++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/batch/BatchPhysicalJoinRuleBase.scala
@@ -192,6 +192,13 @@ trait BatchPhysicalJoinRuleBase {
           (false, false)
       }
     } else {
+      if (
+        tableConfig.get(OptimizerConfigOptions.TABLE_OPTIMIZER_ADAPTIVE_BROADCAST_JOIN_STRATEGY)
+          == OptimizerConfigOptions.AdaptiveBroadcastJoinStrategy.RUNTIME_ONLY
+      ) {
+        return (false, false)
+      }
+
       val leftSize = JoinUtil.binaryRowRelNodeSize(join.getLeft)
       val rightSize = JoinUtil.binaryRowRelNodeSize(join.getRight)
 
diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/batch/BatchPhysicalSortMergeJoinRule.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/batch/BatchPhysicalSortMergeJoinRule.scala
--- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/batch/BatchPhysicalSortMergeJoinRule.scala
+++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/batch/BatchPhysicalSortMergeJoinRule.scala
@@ -22,6 +22,7 @@ import org.apache.flink.table.planner.plan.`trait`.FlinkRelDistribution
 import org.apache.flink.table.planner.plan.nodes.FlinkConventions
 import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalJoin
 import org.apache.flink.table.planner.plan.nodes.physical.batch.BatchPhysicalSortMergeJoin
+import org.apache.flink.table.planner.plan.utils.JoinUtil
 import org.apache.flink.table.planner.utils.ShortcutUtils.unwrapTableConfig
 
 import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall, RelTraitSet}
@@ -72,6 +73,7 @@ class BatchPhysicalSortMergeJoinRule
     val providedTraitSet = call.getPlanner
       .emptyTraitSet()
       .replace(FlinkConventions.BATCH_PHYSICAL)
+    val withJobStrategyHint = JoinUtil.containsJoinStrategyHint(join.getHints)
     // do not try to remove redundant sort for shorter optimization time
     val newJoin = new BatchPhysicalSortMergeJoin(
       join.getCluster,
@@ -81,7 +83,8 @@ class BatchPhysicalSortMergeJoinRule
       join.getCondition,
       join.getJoinType,
       false,
-      false)
+      false,
+      withJobStrategyHint)
     call.transformTo(newJoin)
   }
 }
diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/utils/JoinUtil.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/utils/JoinUtil.scala
--- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/utils/JoinUtil.scala
+++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/utils/JoinUtil.scala
@@ -19,28 +19,36 @@ package org.apache.flink.table.planner.plan.utils
 
 import org.apache.flink.configuration.ReadableConfig
 import org.apache.flink.table.api.TableException
+import org.apache.flink.table.api.config.ExecutionConfigOptions
 import org.apache.flink.table.data.RowData
 import org.apache.flink.table.planner.JDouble
 import org.apache.flink.table.planner.calcite.FlinkTypeFactory
 import org.apache.flink.table.planner.codegen.{CodeGeneratorContext, ExprCodeGenerator, FunctionCodeGenerator}
+import org.apache.flink.table.planner.hint.JoinStrategy
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeConfig
 import org.apache.flink.table.planner.plan.nodes.exec.spec.JoinSpec
 import org.apache.flink.table.planner.plan.nodes.logical.{FlinkLogicalJoin, FlinkLogicalSnapshot}
+import org.apache.flink.table.planner.plan.nodes.physical.batch.BatchPhysicalJoinBase
 import org.apache.flink.table.planner.plan.utils.IntervalJoinUtil.satisfyIntervalJoin
 import org.apache.flink.table.planner.plan.utils.TemporalJoinUtil.satisfyTemporalJoin
 import org.apache.flink.table.planner.plan.utils.WindowJoinUtil.satisfyWindowJoin
 import org.apache.flink.table.runtime.generated.GeneratedJoinCondition
+import org.apache.flink.table.runtime.operators.join.FlinkJoinType
 import org.apache.flink.table.runtime.operators.join.stream.utils.JoinInputSideSpec
 import org.apache.flink.table.runtime.types.PlannerTypeUtils
 import org.apache.flink.table.runtime.typeutils.InternalTypeInfo
 import org.apache.flink.table.types.logical.{LogicalType, RowType}
 
+import com.google.common.collect.ImmutableList
 import org.apache.calcite.plan.RelOptUtil
 import org.apache.calcite.rel.`type`.{RelDataType, RelDataTypeField}
 import org.apache.calcite.rel.RelNode
 import org.apache.calcite.rel.core.{Join, JoinInfo, JoinRelType}
+import org.apache.calcite.rel.hint.RelHint
 import org.apache.calcite.rex.{RexCall, RexInputRef, RexNode, RexUtil}
 import org.apache.calcite.sql.validate.SqlValidatorUtil
 import org.apache.calcite.util.ImmutableIntList
+import org.apache.calcite.util.Util
 
 import java.util
 import java.util.Collections
@@ -275,4 +283,42 @@ object JoinUtil {
       rowCount * FlinkRelMdUtil.binaryRowAverageSize(relNode)
     }
   }
+
+  /**
+   * Get managed memory for hash join. Because hash join may fallback to sort merge join, it takes
+   * larger managed memory to support a HashJoin being converted into a SortMergeJoin.
+   */
+  def getManagedMemory(joinType: FlinkJoinType, config: ExecNodeConfig): Long = {
+    val hashJoinManagedMemory =
+      config.get(ExecutionConfigOptions.TABLE_EXEC_RESOURCE_HASH_JOIN_MEMORY).getBytes
+    // The memory used by SortMergeJoinIterator that buffer the matched rows, each side needs
+    // this memory if it is full outer join
+    val externalBufferMemory =
+      config.get(ExecutionConfigOptions.TABLE_EXEC_RESOURCE_EXTERNAL_BUFFER_MEMORY).getBytes
+    // The memory used by BinaryExternalSorter for sort, the left and right side both need it
+    val sortMemory = config.get(ExecutionConfigOptions.TABLE_EXEC_RESOURCE_SORT_MEMORY).getBytes
+    var externalBufferNum = 1
+    if (joinType eq FlinkJoinType.FULL) {
+      externalBufferNum = 2
+    }
+    val sortMergeJoinManagedMemory = externalBufferMemory * externalBufferNum + sortMemory * 2
+    // Due to hash join maybe fallback to sort merge join, so here managed memory choose the
+    // large one
+    Math.max(hashJoinManagedMemory, sortMergeJoinManagedMemory)
+  }
+
+  /** Get estimated row stats for hash join. */
+  def getEstimatedRowStats(joinBase: BatchPhysicalJoinBase): (Int, Long, Int, Long) = {
+    val mq = joinBase.getCluster.getMetadataQuery
+    val leftRowSize = Util.first(mq.getAverageRowSize(joinBase.getLeft), 24).toInt
+    val leftRowCount = Util.first(mq.getRowCount(joinBase.getLeft), 200000).toLong
+    val rightRowSize = Util.first(mq.getAverageRowSize(joinBase.getRight), 24).toInt
+    val rightRowCount = Util.first(mq.getRowCount(joinBase.getRight), 200000).toLong
+
+    (leftRowSize, leftRowCount, rightRowSize, rightRowCount)
+  }
+
+  def containsJoinStrategyHint(relHints: ImmutableList[RelHint]): Boolean = {
+    relHints.exists(relHint => JoinStrategy.isJoinStrategy(relHint.hintName))
+  }
 }