All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.yahoo.jdisc.ReferencedResource Maven / Gradle / Ivy

There is a newer version: 8.441.21
Show newest version
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc;

/**
 * 

Utility class for working with reference-counted {@link SharedResource}s.

* *

Sometimes, you may want a method to return both a resource object and * a {@link ResourceReference} that refers the resource object (for later release of the resource). * Java methods cannot return multiple objects, so this class provides Pair-like functionality * for returning both.

* *

Example usage:

*
 *     ReferencedResource<MyResource> getResource() {
 *         final ResourceReference ref = resource.refer();
 *         return new ReferencedResource(resource, ref);
 *     }
 *
 *     void useResource() {
 *         final ReferencedResource<MyResource> referencedResource = getResource();
 *         referencedResource.getResource().use();
 *         referencedResource.getReference().close();
 *     }
 * 
* *

This class implements AutoCloseable, so the latter method may also be written as follows:

*
 *     void useResource() {
 *         for (final ReferencedResource<MyResource> referencedResource = getResource()) {
 *             referencedResource.getResource().use();
 *         }
 *     }
 * 
* * @author bakksjo */ public class ReferencedResource implements AutoCloseable { private final T resource; private final ResourceReference reference; public ReferencedResource(final T resource, final ResourceReference reference) { this.resource = resource; this.reference = reference; } public T getResource() { return resource; } public ResourceReference getReference() { return reference; } @Override public void close() { reference.close(); } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy