01: /**
02: * Copyright (C) 2006 Google Inc.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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: */package com.google.inject.util;
16:
17: import java.lang.ref.Reference;
18: import java.lang.ref.ReferenceQueue;
19: import java.util.logging.Level;
20: import java.util.logging.Logger;
21:
22: /**
23: * Starts a background thread that cleans up after reclaimed referents.
24: *
25: * @author Bob Lee (crazybob@google.com)
26: */
27: class FinalizableReferenceQueue extends ReferenceQueue<Object> {
28:
29: private static final Logger logger = Logger
30: .getLogger(FinalizableReferenceQueue.class.getName());
31:
32: private FinalizableReferenceQueue() {
33: }
34:
35: void cleanUp(Reference reference) {
36: try {
37: ((FinalizableReference) reference).finalizeReferent();
38: } catch (Throwable t) {
39: deliverBadNews(t);
40: }
41: }
42:
43: void deliverBadNews(Throwable t) {
44: logger.log(Level.SEVERE, "Error cleaning up after reference.",
45: t);
46: }
47:
48: void start() {
49: Thread thread = new Thread("FinalizableReferenceQueue") {
50: public void run() {
51: while (true) {
52: try {
53: cleanUp(remove());
54: } catch (InterruptedException e) { /* ignore */
55: }
56: }
57: }
58: };
59: thread.setDaemon(true);
60: thread.start();
61: }
62:
63: static final ReferenceQueue<Object> instance = createAndStart();
64:
65: static FinalizableReferenceQueue createAndStart() {
66: FinalizableReferenceQueue queue = new FinalizableReferenceQueue();
67: queue.start();
68: return queue;
69: }
70:
71: /**
72: * Gets instance.
73: */
74: public static ReferenceQueue<Object> getInstance() {
75: return instance;
76: }
77: }
|