Skip to main content
summaryrefslogtreecommitdiffstats
blob: a9ec57f9a0c1558beb8193b0e568346ea08f06ca (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/**
 * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *    Eike Stepper - initial API and implementation
 */
package org.eclipse.net4j.util.cache;

import org.eclipse.net4j.internal.util.bundle.OM;
import org.eclipse.net4j.util.concurrent.Worker;
import org.eclipse.net4j.util.om.trace.ContextTracer;

import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;

/**
 * @author Eike Stepper
 */
public abstract class Cache<E> extends Worker implements ICache
{
  private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, Cache.class);

  private ICacheMonitor cacheMonitor;

  private ICacheProbe cacheProbe;

  private ReferenceQueue<E> referenceQueue = new ReferenceQueue<E>();

  public Cache()
  {
  }

  public ICacheMonitor getCacheMonitor()
  {
    return cacheMonitor;
  }

  public void setCacheMonitor(ICacheMonitor cacheMonitor)
  {
    this.cacheMonitor = cacheMonitor;
  }

  protected ICacheProbe getCacheProbe()
  {
    return cacheProbe;
  }

  protected ReferenceQueue<E> getReferenceQueue()
  {
    return referenceQueue;
  }

  @Override
  protected void doBeforeActivate() throws Exception
  {
    super.doBeforeActivate();
    if (cacheMonitor == null)
    {
      throw new IllegalStateException("cacheMonitor == null"); //$NON-NLS-1$
    }
  }

  @Override
  protected void doActivate() throws Exception
  {
    super.doActivate();
    cacheProbe = cacheMonitor.registerCache(this);
  }

  @Override
  protected void doDeactivate() throws Exception
  {
    cacheMonitor.deregisterCache(this);
    cacheProbe = null;
    super.doDeactivate();
  }

  @Override
  protected void work(WorkContext context) throws Exception
  {
    Reference<? extends E> reference = referenceQueue.remove(200);
    if (reference != null)
    {
      unreachableElement(reference);
    }
  }

  protected void unreachableElement(Reference<? extends E> reference)
  {
    E element = reference.get();
    if (element != null)
    {
      unreachableElement(element);
    }
  }

  protected void unreachableElement(E element)
  {
    if (TRACER.isEnabled())
    {
      TRACER.trace("Unreachable: " + element); //$NON-NLS-1$
    }
  }
}

Back to the top