OLD | NEW |
| (Empty) |
1 /* | |
2 * Copyright (C) 2012 René Jeschke <rene_jeschke@yahoo.de> | |
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.github.rjeschke.neetutils.dispose; | |
17 | |
18 import java.lang.ref.ReferenceQueue; | |
19 import java.lang.ref.WeakReference; | |
20 | |
21 import com.github.rjeschke.neetutils.dispose.ReferenceList.Node; | |
22 | |
23 /** | |
24 * | |
25 * @author René Jeschke (rene_jeschke@yahoo.de) | |
26 * | |
27 */ | |
28 public class Disposer extends WeakReference<Disposable> | |
29 { | |
30 private final Disposable disposable; | |
31 private final Node<Disposer> disposer; | |
32 private volatile boolean disposed = false; | |
33 final static ReferenceQueue<Disposable> refQueue; | |
34 final static ReferenceList<Disposer> disposers; | |
35 | |
36 static | |
37 { | |
38 refQueue = new ReferenceQueue<Disposable>(); | |
39 disposers = new ReferenceList<Disposer>(); | |
40 | |
41 final Thread thread = new Thread(new Cleaner()); | |
42 thread.setName("neetutils-Disposer"); | |
43 thread.setDaemon(true); | |
44 thread.start(); | |
45 } | |
46 | |
47 public Disposer(final Disposable referent, final Disposable disposable) | |
48 { | |
49 super(referent, refQueue); | |
50 this.disposable = disposable; | |
51 synchronized (disposers) | |
52 { | |
53 this.disposer = disposers.add(this); | |
54 } | |
55 } | |
56 | |
57 public void dispose() | |
58 { | |
59 if (!this.disposed) | |
60 { | |
61 synchronized (disposers) | |
62 { | |
63 disposers.remove(this.disposer); | |
64 } | |
65 this.disposed = true; | |
66 this.disposable.dispose(); | |
67 } | |
68 } | |
69 | |
70 public boolean isDisposed() | |
71 { | |
72 return this.disposed; | |
73 } | |
74 | |
75 private static final class Cleaner implements Runnable | |
76 { | |
77 public Cleaner() | |
78 { | |
79 // empty | |
80 } | |
81 | |
82 @Override | |
83 public void run() | |
84 { | |
85 final ReferenceQueue<Disposable> refQueue = Disposer.refQueue; | |
86 for (;;) | |
87 { | |
88 try | |
89 { | |
90 ((Disposer)refQueue.remove()).dispose(); | |
91 } | |
92 catch (final Throwable t) | |
93 { | |
94 // | |
95 } | |
96 } | |
97 } | |
98 } | |
99 } | |
OLD | NEW |