• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2022 Google LLC
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.google.android.libraries.mobiledatadownload.file.common;
17 
18 import java.io.Closeable;
19 import java.io.IOException;
20 import javax.annotation.Nullable;
21 
22 /**
23  * A wrapper for a Closeable resource that allows caller to free that resource from a
24  * try-with-resources block.
25  */
26 public final class ReleasableResource<T extends Closeable> implements Closeable {
27   @Nullable private T resource;
28 
ReleasableResource(T resource)29   private ReleasableResource(T resource) {
30     this.resource = resource;
31   }
32 
33   /**
34    * Creates a ReleasableResource wrapped around a resource.
35    *
36    * @param resource the Closeable resource.
37    */
create(T resource)38   public static <T extends Closeable> ReleasableResource<T> create(T resource) {
39     return new ReleasableResource<T>(resource);
40   }
41 
42   /**
43    * Returns the wrapped resource and releases ownership. The caller is responsible for ensuring the
44    * resource is closed.
45    *
46    * @return the wrapped resource.
47    */
48   @Nullable
release()49   public T release() {
50     T freed = resource;
51     resource = null;
52     return freed;
53   }
54 
55   /**
56    * Returns the wrapped resource but does not release ownership.
57    *
58    * @return the wrapped resource.
59    */
60   @Nullable
get()61   public T get() {
62     return resource;
63   }
64 
65   @Override
close()66   public void close() throws IOException {
67     if (resource != null) {
68       resource.close();
69     }
70   }
71 }
72