|
| 1 | +/******************************************************************************* |
| 2 | + * Copyright (c) 2025 Eclipse RDF4J contributors. |
| 3 | + * |
| 4 | + * All rights reserved. This program and the accompanying materials |
| 5 | + * are made available under the terms of the Eclipse Distribution License v1.0 |
| 6 | + * which accompanies this distribution, and is available at |
| 7 | + * http://www.eclipse.org/org/documents/edl-v10.php. |
| 8 | + * |
| 9 | + * SPDX-License-Identifier: BSD-3-Clause |
| 10 | + *******************************************************************************/ |
| 11 | +package org.eclipse.rdf4j.repository.sparql; |
| 12 | + |
| 13 | +import static org.assertj.core.api.Assertions.assertThat; |
| 14 | + |
| 15 | +import java.lang.reflect.Field; |
| 16 | +import java.util.concurrent.ExecutorService; |
| 17 | +import java.util.concurrent.TimeUnit; |
| 18 | + |
| 19 | +import org.eclipse.rdf4j.http.client.SharedHttpClientSessionManager; |
| 20 | +import org.eclipse.rdf4j.repository.RepositoryConnection; |
| 21 | +import org.junit.jupiter.api.Test; |
| 22 | + |
| 23 | +/** |
| 24 | + * Verifies that a SPARQLRepository performs internal shutdown when it becomes unreachable. |
| 25 | + * |
| 26 | + * <p> |
| 27 | + * This test intentionally does not call {@code repository.shutDown()}. It expects the repository to arrange for its |
| 28 | + * internal {@code shutDownInternal()} to run when the object is no longer reachable (e.g., by using Java 9 Cleaner). |
| 29 | + * </p> |
| 30 | + */ |
| 31 | +public class SPARQLRepositoryCleanerTest { |
| 32 | + |
| 33 | + @Test |
| 34 | + void autoShutdownOnUnreachable() throws Exception { |
| 35 | + SPARQLRepository repo = new SPARQLRepository("http://example.org/sparql"); |
| 36 | + |
| 37 | + // Ensure dependent client is created |
| 38 | + try (RepositoryConnection conn = repo.getConnection()) { |
| 39 | + // no-op |
| 40 | + } |
| 41 | + |
| 42 | + SharedHttpClientSessionManager mgr = (SharedHttpClientSessionManager) repo.getHttpClientSessionManager(); |
| 43 | + |
| 44 | + // Access internal executor to verify shutdown state |
| 45 | + Field f = SharedHttpClientSessionManager.class.getDeclaredField("executor"); |
| 46 | + f.setAccessible(true); |
| 47 | + ExecutorService exec = (ExecutorService) f.get(mgr); |
| 48 | + |
| 49 | + // Drop strong reference and encourage GC to trigger Cleaner |
| 50 | + repo = null; |
| 51 | + |
| 52 | + boolean cleaned = false; |
| 53 | + for (int i = 0; i < 40 && !cleaned; i++) { |
| 54 | + System.gc(); |
| 55 | + System.runFinalization(); |
| 56 | + TimeUnit.MILLISECONDS.sleep(100); |
| 57 | + cleaned = exec.isShutdown() || exec.isTerminated(); |
| 58 | + } |
| 59 | + |
| 60 | + assertThat(cleaned) |
| 61 | + .as("dependent session manager executor should be shut down by Cleaner") |
| 62 | + .isTrue(); |
| 63 | + } |
| 64 | +} |
0 commit comments