01: /**
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */package org.apache.solr.util;
17:
18: import java.util.concurrent.atomic.AtomicInteger;
19:
20: /** Keep track of a reference count on a resource and close it when
21: * the count hits zero.
22: *
23: * By itself, this class could have some race conditions
24: * since there is no synchronization between the refcount
25: * check and the close. Solr's use in reference counting searchers
26: * is safe since the count can only hit zero if it's unregistered (and
27: * hence incref() will not be called again on it).
28: *
29: * @author yonik
30: * @version $Id: RefCounted.java 542583 2007-05-29 16:33:23Z yonik $
31: */
32:
33: public abstract class RefCounted<Type> {
34: protected final Type resource;
35: protected final AtomicInteger refcount = new AtomicInteger();
36:
37: public RefCounted(Type resource) {
38: this .resource = resource;
39: }
40:
41: public final RefCounted<Type> incref() {
42: refcount.incrementAndGet();
43: return this ;
44: }
45:
46: public final Type get() {
47: return resource;
48: }
49:
50: public void decref() {
51: if (refcount.decrementAndGet() == 0) {
52: close();
53: }
54: }
55:
56: protected abstract void close();
57: }
|