Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 6c85849b2b17007440938c3aa7437abe814ea5d8 (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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
/*
 * Copyright (c) 2004 - 2012 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:
 *    Ed Merks - initial API and implementation
 */
package org.eclipse.net4j.util.ref;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;

/**
 * @author Ed Merks
 * @since 3.3
 */
public class Interner<E>
{
  private static final int[] PRIME_CAPACITIES = new int[] { 17, 37, 67, 131, 257, 521, 1031, 2053, 4099, 8209, 16411,
      32771, 65537, 131101, 262147, 524309, 1048583, 2097169, 4194319, 8388617, 16777259, 33554467, 67108879,
      134217757, 268435459, 536870923, 1073741827, 2147483629 };

  private int size;

  private int capacityIndex;

  private Entry<E>[] entries;

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

  public Interner()
  {
  }

  public E intern(E object)
  {
    cleanup();

    int hashCode = hashCode(object);
    if (entries != null)
    {
      int index = index(hashCode);
      for (Entry<E> entry = entries[index]; entry != null; entry = entry.next)
      {
        if (hashCode == entry.hashCode)
        {
          E otherObject = entry.get();
          if (equals(object, otherObject))
          {
            return otherObject;
          }
        }
      }
    }

    Entry<E> entry = createEntry(object, hashCode);
    addEntry(entry);
    return object;
  }

  /**
   * Gets the first entry in the table with exactly the given hash code.
   * It's very useful to call {@link Entry#getNextEntry()} to yield the next entry with exactly this same hash code.
   */
  protected Entry<E> getEntry(int hashCode)
  {
    cleanup();

    if (entries != null)
    {
      int index = index(hashCode);
      for (Entry<E> entry = entries[index]; entry != null; entry = entry.next)
      {
        if (hashCode == entry.hashCode)
        {
          return entry;
        }
      }
    }

    return null;
  }

  protected int hashCode(E object)
  {
    return object.hashCode();
  }

  /**
   * Returns true if the two objects are to be considered equal.
   * The first object will always be the one passed in as an argument to {@link #add(Object) add},
   * {@link #contains(Object) contains}, {@link #get(Object) get}, {@link #intern(Object)}, {@link #remove(Object)}.
   */
  protected boolean equals(E object, E otherObject)
  {
    return object == otherObject || object.equals(otherObject);
  }

  protected Entry<E> createEntry(E object, int hashCode)
  {
    return new Entry<E>(object, hashCode, queue);
  }

  /**
   * Adds a new entry, {@link #ensureCapacity() ensures} the capacity is sufficient and increases the {@link #size}.
   */
  protected void addEntry(Entry<E> entry)
  {
    ensureCapacity();
    ++size;
    putEntry(entry);
  }

  private Entry<E>[] newEntries(int capacity)
  {
    @SuppressWarnings("unchecked")
    Entry<E>[] newEntries = new Entry[capacity];
    return newEntries;
  }

  private void ensureCapacity()
  {
    int capacity = PRIME_CAPACITIES[capacityIndex];
    if (entries == null)
    {
      entries = newEntries(capacity);
    }
    else if (size > (capacity >> 2) * 3)
    {
      // The current size is more the 3/4 of the current capacity
      ++capacityIndex;
      rehash(newEntries(PRIME_CAPACITIES[capacityIndex]));
    }
  }

  private void rehash(Entry<E>[] newEntries)
  {
    Entry<E>[] oldEntries = entries;
    entries = newEntries;
    if (oldEntries != null)
    {
      for (int i = 0, length = oldEntries.length; i < length; ++i)
      {
        Entry<E> entry = oldEntries[i];
        while (entry != null)
        {
          Entry<E> nextEntry = entry.next;
          putEntry(entry);
          entry = nextEntry;
        }
      }
    }
  }

  private int index(int hashCode)
  {
    return (hashCode & 0x7FFFFFFF) % entries.length;
  }

  private void putEntry(Entry<E> entry)
  {
    int index = index(entry.hashCode);
    Entry<E> otherEntry = entries[index];
    entries[index] = entry;
    entry.next = otherEntry;
  }

  private void cleanup()
  {
    for (;;)
    {
      @SuppressWarnings("unchecked")
      Entry<E> entry = (Entry<E>)queue.poll();
      if (entry == null)
      {
        return;
      }

      removeEntry(entry);
    }
  }

  private void removeEntry(Entry<E> entry)
  {
    int index = index(entry.hashCode);
    Entry<E> otherEntry = entries[index];
    --size;
    if (entry == otherEntry)
    {
      entries[index] = entry.next;
    }
    else
    {
      for (Entry<E> nextOtherEntry = otherEntry.next; nextOtherEntry != null; otherEntry = nextOtherEntry, nextOtherEntry = nextOtherEntry.next)
      {
        if (nextOtherEntry == entry)
        {
          otherEntry.next = entry.next;
          break;
        }
      }
    }

    // Make life easier for the garbage collector.
    entry.next = null;
    entry.clear();
  }

  /**
   * A weak reference holder that caches the hash code of the referent and is chained in the {@link Interner#entries} to handle collisions.
   *
   * @author Ed Merks
   */
  protected static class Entry<E> extends WeakReference<E>
  {
    public final int hashCode;

    public Entry<E> next;

    public Entry(E object, int hashCode, ReferenceQueue<? super E> queue)
    {
      super(object, queue);
      this.hashCode = hashCode;
    }

    public Entry<E> getNextEntry()
    {
      for (Entry<E> entry = next; entry != null; entry = entry.next)
      {
        if (entry.hashCode == hashCode)
        {
          return entry;
        }
      }

      return null;
    }

    @Override
    public String toString()
    {
      E object = get();
      return object == null ? "null" : object.toString();
    }
  }
}

Back to the top