Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 49478fcd6e825750e07efb485524be207f6a0df4 (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
/*
 * Copyright (c) 2015 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
 *    Simon McDuff - bug 201266
 *    Simon McDuff - bug 230832
 */
package org.eclipse.net4j.util.ref;

import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author Eike Stepper
 * @since 3.6
 */
public abstract class CleanableReferenceQueue<T> extends ReferenceQueue<T>
{
  public static final int ALL_WORK_PER_POLL = ReferenceQueueWorker.ALL_WORK_PER_POLL;

  public static final int DEFAULT_MAX_WORK_PER_POLL = ReferenceQueueWorker.DEFAULT_MAX_WORK_PER_POLL;

  public static final int DEFAULT_POLL_MILLIS = ReferenceQueueWorker.DEFAULT_POLL_MILLIS;

  private final AtomicBoolean cleaning = new AtomicBoolean();

  private int maxWorkPerPoll;

  private long pollMillis;

  private long lastPoll = System.currentTimeMillis();

  public CleanableReferenceQueue()
  {
    setPollMillis(DEFAULT_POLL_MILLIS);
    setMaxWorkPerPoll(DEFAULT_MAX_WORK_PER_POLL);
  }

  public final long getPollMillis()
  {
    return pollMillis;
  }

  public final void setPollMillis(long pollMillis)
  {
    this.pollMillis = pollMillis;
  }

  public final int getMaxWorkPerPoll()
  {
    return maxWorkPerPoll;
  }

  public final void setMaxWorkPerPoll(int maxWorkPerPoll)
  {
    this.maxWorkPerPoll = maxWorkPerPoll;
  }

  public final void register(T object)
  {
    clean();
    createReference(object);
  }

  public final void clean()
  {
    if (cleaning.compareAndSet(false, true))
    {
      long now = System.currentTimeMillis();
      if (lastPoll + pollMillis > now)
      {
        int count = maxWorkPerPoll;
        if (count == ALL_WORK_PER_POLL)
        {
          count = Integer.MAX_VALUE;
        }

        for (int i = 0; i < count; i++)
        {
          Reference<? extends T> reference = poll();
          if (reference == null)
          {
            break;
          }

          cleanReference(reference);
        }

        lastPoll = now;
      }

      cleaning.set(false);
    }
  }

  protected abstract void cleanReference(Reference<? extends T> reference);

  protected abstract Reference<T> createReference(T object);
}

Back to the top