@@ -193,6 +193,10 @@ public static Builder builderForNonStartableContext() {
193
193
* @throws Exception if there is an error closing the resources
194
194
*/
195
195
public void close () throws Exception {
196
+ callCloseables (closeables );
197
+ }
198
+
199
+ private static void callCloseables (List <AutoCloseable > closeables ) {
196
200
for (int i = closeables .size () - 1 ; i >= 0 ; i --) {
197
201
try {
198
202
closeables .get (i ).close ();
@@ -226,6 +230,7 @@ public static class Builder {
226
230
protected ServiceConfiguration svcConfig = initializeConfig ();
227
231
protected Consumer <ServiceConfiguration > configOverrideCustomizer = this ::defaultOverrideServiceConfiguration ;
228
232
protected Function <BrokerService , BrokerService > brokerServiceCustomizer = Function .identity ();
233
+ protected PulsarTestContext otherContextToClose ;
229
234
230
235
/**
231
236
* Initialize the ServiceConfiguration with default values.
@@ -401,7 +406,15 @@ public Builder reuseSpyConfig(PulsarTestContext otherContext) {
401
406
* The other PulsarTestContext will be closed when this one is closed.
402
407
*/
403
408
public Builder chainClosing (PulsarTestContext otherContext ) {
404
- registerCloseable (otherContext );
409
+ otherContextToClose = otherContext ;
410
+ return this ;
411
+ }
412
+
413
+ /**
414
+ * Registers a closeable to close as the last one by prepending it to the closeables list.
415
+ */
416
+ public Builder prependCloseable (AutoCloseable closeable ) {
417
+ closeables .add (0 , closeable );
405
418
return this ;
406
419
}
407
420
@@ -537,9 +550,14 @@ public final PulsarTestContext build() {
537
550
try {
538
551
super .pulsarService .start ();
539
552
} catch (Exception e ) {
553
+ callCloseables (super .closeables );
554
+ super .closeables .clear ();
540
555
throw new RuntimeException (e );
541
556
}
542
557
}
558
+ if (otherContextToClose != null ) {
559
+ prependCloseable (otherContextToClose );
560
+ }
543
561
brokerService (super .pulsarService .getBrokerService ());
544
562
return super .build ();
545
563
}
0 commit comments