KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > google > inject > util > FinalizableReferenceQueue


1 /**
2  * Copyright (C) 2006 Google Inc.
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
17 package com.google.inject.util;
18
19 import java.lang.ref.Reference JavaDoc;
20 import java.lang.ref.ReferenceQueue JavaDoc;
21 import java.util.logging.Level JavaDoc;
22 import java.util.logging.Logger JavaDoc;
23
24 /**
25  * Starts a background thread that cleans up after reclaimed referents.
26  *
27  * @author Bob Lee (crazybob@google.com)
28  */

29 class FinalizableReferenceQueue extends ReferenceQueue JavaDoc<Object JavaDoc> {
30
31   private static final Logger JavaDoc logger =
32       Logger.getLogger(FinalizableReferenceQueue.class.getName());
33
34   private FinalizableReferenceQueue() {}
35
36   void cleanUp(Reference JavaDoc reference) {
37     try {
38       ((FinalizableReference) reference).finalizeReferent();
39     } catch (Throwable JavaDoc t) {
40       deliverBadNews(t);
41     }
42   }
43
44   void deliverBadNews(Throwable JavaDoc t) {
45     logger.log(Level.SEVERE, "Error cleaning up after reference.", t);
46   }
47
48   void start() {
49     Thread JavaDoc thread = new Thread JavaDoc("FinalizableReferenceQueue") {
50       public void run() {
51         while (true) {
52           try {
53             cleanUp(remove());
54           } catch (InterruptedException JavaDoc e) { /* ignore */ }
55         }
56       }
57     };
58     thread.setDaemon(true);
59     thread.start();
60   }
61
62   static final ReferenceQueue JavaDoc<Object JavaDoc> instance = createAndStart();
63
64   static FinalizableReferenceQueue createAndStart() {
65     FinalizableReferenceQueue queue = new FinalizableReferenceQueue();
66     queue.start();
67     return queue;
68   }
69
70   /**
71    * Gets instance.
72    */

73   public static ReferenceQueue JavaDoc<Object JavaDoc> getInstance() {
74     return instance;
75   }
76 }
77
Popular Tags