View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.buildcache.hash;
20  
21  import java.nio.ByteBuffer;
22  import java.util.concurrent.ConcurrentHashMap;
23  import java.util.concurrent.ConcurrentMap;
24  
25  /**
26   * ThreadLocalBuffer
27   */
28  public class ThreadLocalBuffer {
29  
30      private static final ConcurrentMap<CloseableBuffer, Boolean> LOCALS = new ConcurrentHashMap<>();
31  
32      public static ByteBuffer get(ThreadLocal<CloseableBuffer> local, int capacity) {
33          final CloseableBuffer buffer = local.get();
34          if (buffer == null) {
35              return create(local, capacity);
36          }
37  
38          if (capacity(buffer) < capacity) {
39              close(buffer);
40              return create(local, capacity * 2);
41          }
42  
43          return clear(buffer);
44      }
45  
46      @Override
47      public void finalize() {
48          for (CloseableBuffer buffer : LOCALS.keySet()) {
49              buffer.close();
50          }
51      }
52  
53      private static ByteBuffer create(ThreadLocal<CloseableBuffer> local, int capacity) {
54          final CloseableBuffer buffer = CloseableBuffer.directBuffer(capacity);
55          local.set(buffer);
56          LOCALS.put(buffer, false);
57          return buffer.getBuffer();
58      }
59  
60      private static int capacity(CloseableBuffer buffer) {
61          return buffer.getBuffer().capacity();
62      }
63  
64      private static ByteBuffer clear(CloseableBuffer buffer) {
65          return (ByteBuffer) buffer.getBuffer().clear();
66      }
67  
68      private static void close(CloseableBuffer buffer) {
69          LOCALS.remove(buffer);
70          buffer.close();
71      }
72  
73      private ThreadLocalBuffer() {}
74  }