This class provides a wrapper around Jar that uses reference counting to close and re-create the wrapped Jar instance as required.
| 28 | * {@link Jar} instance as required. |
| 29 | */ |
| 30 | public class ReferenceCountedJar implements Jar { |
| 31 | |
| 32 | private final URL url; |
| 33 | private Jar wrappedJar; |
| 34 | private int referenceCount = 0; |
| 35 | |
| 36 | /** |
| 37 | * Creates a new reference-counted wrapper for the JAR at the given URL. |
| 38 | * |
| 39 | * @param url the URL of the JAR file |
| 40 | * |
| 41 | * @throws IOException if the JAR cannot be opened |
| 42 | */ |
| 43 | public ReferenceCountedJar(URL url) throws IOException { |
| 44 | this.url = url; |
| 45 | open(); |
| 46 | } |
| 47 | |
| 48 | |
| 49 | /* |
| 50 | * Note: Returns this instance so it can be used with try-with-resources |
| 51 | */ |
| 52 | private synchronized ReferenceCountedJar open() throws IOException { |
| 53 | if (wrappedJar == null) { |
| 54 | wrappedJar = JarFactory.newInstance(url); |
| 55 | } |
| 56 | referenceCount++; |
| 57 | return this; |
| 58 | } |
| 59 | |
| 60 | |
| 61 | @Override |
| 62 | public synchronized void close() { |
| 63 | referenceCount--; |
| 64 | if (referenceCount == 0) { |
| 65 | wrappedJar.close(); |
| 66 | wrappedJar = null; |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | |
| 71 | @Override |
| 72 | public URL getJarFileURL() { |
| 73 | return url; |
| 74 | } |
| 75 | |
| 76 | |
| 77 | @Override |
| 78 | public InputStream getInputStream(String name) throws IOException { |
| 79 | try (ReferenceCountedJar jar = open()) { |
| 80 | return jar.wrappedJar.getInputStream(name); |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | |
| 85 | @Override |
| 86 | public long getLastModified(String name) throws IOException { |
| 87 | try (ReferenceCountedJar jar = open()) { |
nothing calls this directly
no outgoing calls
no test coverage detected