@@ -205,6 +205,7 @@ public void mmapSegments(TableMetadata metadata, @Transient Path walPath, long w
205205 if (fdCacheKey < 0 ) {
206206 fds = walFdCache .valueAt (fdCacheKey );
207207 }
208+ int initialSize = walMappedColumns .size ();
208209
209210 try {
210211 int file = 0 ;
@@ -293,8 +294,23 @@ public void mmapSegments(TableMetadata metadata, @Transient Path walPath, long w
293294 }
294295 }
295296 } catch (Throwable th ) {
296- closeWalFiles (true , walSegmentId , 0 );
297+ closeWalFiles (true , walSegmentId , initialSize );
298+ walMappedColumns .setPos (initialSize ); // already done by closeWalFiles(); kept for clarity
299+ // Avoid double removal/pool push by the finally block when cached FDs were consumed.
300+ fds = null ;
297301 throw th ;
302+ } finally {
303+ // Now that the FDs are used in the column objects, remove them from the cache.
304+ // to avoid double close in case of exceptions.
305+ if (fdCacheKey < 0 ) {
306+ walFdCache .removeAt (fdCacheKey );
307+ walFdCacheSize --;
308+ }
309+
310+ if (fds != null ) {
311+ fds .clear ();
312+ walFdCacheListPool .push (fds );
313+ }
298314 }
299315 }
300316
@@ -312,14 +328,21 @@ public void mmapWalColumns(TableWriterSegmentCopyInfo segmentCopyInfo, TableMeta
312328 try {
313329 path .concat (WalUtils .WAL_NAME_BASE );
314330 int walBaseLen = path .size ();
315- for (int i = 0 ; i < segmentCopyInfo .getSegmentCount (); i ++) {
316- int walId = segmentCopyInfo .getWalId (i );
317- int segmentId = segmentCopyInfo .getSegmentId (i );
318- path .trimTo (walBaseLen ).put (walId ).put (SEPARATOR ).put (segmentId );
319- long rowLo = segmentCopyInfo .getRowLo (i );
320- long rowHi = segmentCopyInfo .getRowHi (i );
321- long walIdSegmentId = Numbers .encodeLowHighInts (segmentId , walId );
322- mmapSegments (metadata , path , walIdSegmentId , rowLo , rowHi );
331+ try {
332+ for (int i = 0 , n = segmentCopyInfo .getSegmentCount (); i < n ; i ++) {
333+ int walId = segmentCopyInfo .getWalId (i );
334+ int segmentId = segmentCopyInfo .getSegmentId (i );
335+ path .trimTo (walBaseLen ).put (walId ).put (SEPARATOR ).put (segmentId );
336+ long rowLo = segmentCopyInfo .getRowLo (i );
337+ long rowHi = segmentCopyInfo .getRowHi (i );
338+ long walIdSegmentId = Numbers .encodeLowHighInts (segmentId , walId );
339+ mmapSegments (metadata , path , walIdSegmentId , rowLo , rowHi );
340+ }
341+ } catch (Throwable th ) {
342+ // Close all the columns without placing into the cache.
343+ Misc .freeObjListAndClear (walMappedColumns );
344+ closeWalFiles ();
345+ throw th ;
323346 }
324347 } finally {
325348 path .trimTo (pathSize1 );
0 commit comments