OLD | NEW |
(Empty) | |
| 1 /* |
| 2 * This file is part of Adblock Plus <http://adblockplus.org/>, |
| 3 * Copyright (C) 2006-2014 Eyeo GmbH |
| 4 * |
| 5 * Adblock Plus is free software: you can redistribute it and/or modify |
| 6 * it under the terms of the GNU General Public License version 3 as |
| 7 * published by the Free Software Foundation. |
| 8 * |
| 9 * Adblock Plus is distributed in the hope that it will be useful, |
| 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 * GNU General Public License for more details. |
| 13 * |
| 14 * You should have received a copy of the GNU General Public License |
| 15 * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. |
| 16 */ |
| 17 |
| 18 package org.adblockplus.libadblockplus; |
| 19 |
| 20 import java.lang.ref.ReferenceQueue; |
| 21 import java.lang.ref.WeakReference; |
| 22 import java.util.HashSet; |
| 23 |
| 24 public final class Disposer extends WeakReference<Disposable> |
| 25 { |
| 26 static final ReferenceQueue<Disposable> referenceQueue = new ReferenceQueue<Di
sposable>(); |
| 27 private static final HashSet<Disposer> disposerSet = new HashSet<Disposer>(); |
| 28 private final Disposable disposable; |
| 29 private volatile boolean disposed = false; |
| 30 |
| 31 static |
| 32 { |
| 33 final Thread thread = new Thread(new Cleaner()); |
| 34 thread.setName(Cleaner.class.getCanonicalName()); |
| 35 thread.setDaemon(true); |
| 36 thread.start(); |
| 37 } |
| 38 |
| 39 public Disposer(final Disposable referent, final Disposable disposable) |
| 40 { |
| 41 super(referent, referenceQueue); |
| 42 this.disposable = disposable; |
| 43 |
| 44 synchronized (disposerSet) |
| 45 { |
| 46 disposerSet.add(this); |
| 47 } |
| 48 } |
| 49 |
| 50 public synchronized void dispose() |
| 51 { |
| 52 if (!this.disposed) |
| 53 { |
| 54 try |
| 55 { |
| 56 this.disposable.dispose(); |
| 57 } |
| 58 catch (final Throwable t) |
| 59 { |
| 60 // catch to set state to 'disposed' on all circumstances |
| 61 } |
| 62 |
| 63 this.disposed = true; |
| 64 synchronized (disposerSet) |
| 65 { |
| 66 disposerSet.remove(this); |
| 67 } |
| 68 } |
| 69 } |
| 70 |
| 71 private static final class Cleaner implements Runnable |
| 72 { |
| 73 public Cleaner() |
| 74 { |
| 75 // |
| 76 } |
| 77 |
| 78 @Override |
| 79 public void run() |
| 80 { |
| 81 for (;;) |
| 82 { |
| 83 try |
| 84 { |
| 85 ((Disposer) Disposer.referenceQueue.remove()).dispose(); |
| 86 } |
| 87 catch (final Throwable t) |
| 88 { |
| 89 // ignored |
| 90 } |
| 91 } |
| 92 } |
| 93 } |
| 94 } |
OLD | NEW |