WeakHashMap.java 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. /* WeakHashMap -- a hashtable that keeps only weak references
  2. to its keys, allowing the virtual machine to reclaim them
  3. Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
  4. This file is part of GNU Classpath.
  5. GNU Classpath is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. GNU Classpath is distributed in the hope that it will be useful, but
  10. WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with GNU Classpath; see the file COPYING. If not, write to the
  15. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  16. 02110-1301 USA.
  17. Linking this library statically or dynamically with other modules is
  18. making a combined work based on this library. Thus, the terms and
  19. conditions of the GNU General Public License cover the whole
  20. combination.
  21. As a special exception, the copyright holders of this library give you
  22. permission to link this library with independent modules to produce an
  23. executable, regardless of the license terms of these independent
  24. modules, and to copy and distribute the resulting executable under
  25. terms of your choice, provided that you also meet, for each linked
  26. independent module, the terms and conditions of the license of that
  27. module. An independent module is a module which is not derived from
  28. or based on this library. If you modify this library, you may extend
  29. this exception to your version of the library, but you are not
  30. obligated to do so. If you do not wish to do so, delete this
  31. exception statement from your version. */
  32. package java.util;
  33. import java.lang.ref.ReferenceQueue;
  34. import java.lang.ref.WeakReference;
  35. /**
  36. * A weak hash map has only weak references to the key. This means that it
  37. * allows the key to be garbage collected if it is not used otherwise. If
  38. * this happens, the entry will eventually disappear from the map,
  39. * asynchronously.
  40. *
  41. * <p>A weak hash map makes most sense when the keys doesn't override the
  42. * <code>equals</code> method: If there is no other reference to the
  43. * key nobody can ever look up the key in this table and so the entry
  44. * can be removed. This table also works when the <code>equals</code>
  45. * method is overloaded, such as String keys, but you should be prepared
  46. * to deal with some entries disappearing spontaneously.
  47. *
  48. * <p>Other strange behaviors to be aware of: The size of this map may
  49. * spontaneously shrink (even if you use a synchronized map and synchronize
  50. * it); it behaves as if another thread removes entries from this table
  51. * without synchronization. The entry set returned by <code>entrySet</code>
  52. * has similar phenomenons: The size may spontaneously shrink, or an
  53. * entry, that was in the set before, suddenly disappears.
  54. *
  55. * <p>A weak hash map is not meant for caches; use a normal map, with
  56. * soft references as values instead, or try {@link LinkedHashMap}.
  57. *
  58. * <p>The weak hash map supports null values and null keys. The null key
  59. * is never deleted from the map (except explictly of course). The
  60. * performance of the methods are similar to that of a hash map.
  61. *
  62. * <p>The value objects are strongly referenced by this table. So if a
  63. * value object maintains a strong reference to the key (either direct
  64. * or indirect) the key will never be removed from this map. According
  65. * to Sun, this problem may be fixed in a future release. It is not
  66. * possible to do it with the jdk 1.2 reference model, though.
  67. *
  68. * @author Jochen Hoenicke
  69. * @author Eric Blake (ebb9@email.byu.edu)
  70. * @author Tom Tromey (tromey@redhat.com)
  71. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  72. *
  73. * @see HashMap
  74. * @see WeakReference
  75. * @see LinkedHashMap
  76. * @since 1.2
  77. * @status updated to 1.4 (partial 1.5)
  78. */
  79. public class WeakHashMap<K,V> extends AbstractMap<K,V>
  80. {
  81. // WARNING: WeakHashMap is a CORE class in the bootstrap cycle. See the
  82. // comments in vm/reference/java/lang/Runtime for implications of this fact.
  83. /**
  84. * The default capacity for an instance of HashMap.
  85. * Sun's documentation mildly suggests that this (11) is the correct
  86. * value.
  87. */
  88. private static final int DEFAULT_CAPACITY = 11;
  89. /**
  90. * The default load factor of a HashMap.
  91. */
  92. private static final float DEFAULT_LOAD_FACTOR = 0.75F;
  93. /**
  94. * This is used instead of the key value <i>null</i>. It is needed
  95. * to distinguish between an null key and a removed key.
  96. */
  97. // Package visible for use by nested classes.
  98. static final Object NULL_KEY = new Object()
  99. {
  100. /**
  101. * Sets the hashCode to 0, since that's what null would map to.
  102. * @return the hash code 0
  103. */
  104. public int hashCode()
  105. {
  106. return 0;
  107. }
  108. /**
  109. * Compares this key to the given object. Normally, an object should
  110. * NEVER compare equal to null, but since we don't publicize NULL_VALUE,
  111. * it saves bytecode to do so here.
  112. * @return true iff o is this or null
  113. */
  114. public boolean equals(Object o)
  115. {
  116. return null == o || this == o;
  117. }
  118. };
  119. /**
  120. * The reference queue where our buckets (which are WeakReferences) are
  121. * registered to.
  122. */
  123. private final ReferenceQueue queue;
  124. /**
  125. * The number of entries in this hash map.
  126. */
  127. // Package visible for use by nested classes.
  128. int size;
  129. /**
  130. * The load factor of this WeakHashMap. This is the maximum ratio of
  131. * size versus number of buckets. If size grows the number of buckets
  132. * must grow, too.
  133. */
  134. private float loadFactor;
  135. /**
  136. * The rounded product of the capacity (i.e. number of buckets) and
  137. * the load factor. When the number of elements exceeds the
  138. * threshold, the HashMap calls <code>rehash()</code>.
  139. */
  140. private int threshold;
  141. /**
  142. * The number of structural modifications. This is used by
  143. * iterators, to see if they should fail. This doesn't count
  144. * the silent key removals, when a weak reference is cleared
  145. * by the garbage collection. Instead the iterators must make
  146. * sure to have strong references to the entries they rely on.
  147. */
  148. // Package visible for use by nested classes.
  149. int modCount;
  150. /**
  151. * The entry set. There is only one instance per hashmap, namely
  152. * theEntrySet. Note that the entry set may silently shrink, just
  153. * like the WeakHashMap.
  154. */
  155. private final class WeakEntrySet extends AbstractSet
  156. {
  157. /**
  158. * Non-private constructor to reduce bytecode emitted.
  159. */
  160. WeakEntrySet()
  161. {
  162. }
  163. /**
  164. * Returns the size of this set.
  165. *
  166. * @return the set size
  167. */
  168. public int size()
  169. {
  170. return size;
  171. }
  172. /**
  173. * Returns an iterator for all entries.
  174. *
  175. * @return an Entry iterator
  176. */
  177. public Iterator iterator()
  178. {
  179. return new Iterator()
  180. {
  181. /**
  182. * The entry that was returned by the last
  183. * <code>next()</code> call. This is also the entry whose
  184. * bucket should be removed by the <code>remove</code> call. <br>
  185. *
  186. * It is null, if the <code>next</code> method wasn't
  187. * called yet, or if the entry was already removed. <br>
  188. *
  189. * Remembering this entry here will also prevent it from
  190. * being removed under us, since the entry strongly refers
  191. * to the key.
  192. */
  193. WeakBucket.WeakEntry lastEntry;
  194. /**
  195. * The entry that will be returned by the next
  196. * <code>next()</code> call. It is <code>null</code> if there
  197. * is no further entry. <br>
  198. *
  199. * Remembering this entry here will also prevent it from
  200. * being removed under us, since the entry strongly refers
  201. * to the key.
  202. */
  203. WeakBucket.WeakEntry nextEntry = findNext(null);
  204. /**
  205. * The known number of modification to the list, if it differs
  206. * from the real number, we throw an exception.
  207. */
  208. int knownMod = modCount;
  209. /**
  210. * Check the known number of modification to the number of
  211. * modifications of the table. If it differs from the real
  212. * number, we throw an exception.
  213. * @throws ConcurrentModificationException if the number
  214. * of modifications doesn't match.
  215. */
  216. private void checkMod()
  217. {
  218. // This method will get inlined.
  219. cleanQueue();
  220. if (knownMod != modCount)
  221. throw new ConcurrentModificationException(knownMod + " != "
  222. + modCount);
  223. }
  224. /**
  225. * Get a strong reference to the next entry after
  226. * lastBucket.
  227. * @param lastEntry the previous bucket, or null if we should
  228. * get the first entry.
  229. * @return the next entry.
  230. */
  231. private WeakBucket.WeakEntry findNext(WeakBucket.WeakEntry lastEntry)
  232. {
  233. int slot;
  234. WeakBucket nextBucket;
  235. if (lastEntry != null)
  236. {
  237. nextBucket = lastEntry.getBucket().next;
  238. slot = lastEntry.getBucket().slot;
  239. }
  240. else
  241. {
  242. nextBucket = buckets[0];
  243. slot = 0;
  244. }
  245. while (true)
  246. {
  247. while (nextBucket != null)
  248. {
  249. WeakBucket.WeakEntry entry = nextBucket.getEntry();
  250. if (entry != null)
  251. // This is the next entry.
  252. return entry;
  253. // Entry was cleared, try next.
  254. nextBucket = nextBucket.next;
  255. }
  256. slot++;
  257. if (slot == buckets.length)
  258. // No more buckets, we are through.
  259. return null;
  260. nextBucket = buckets[slot];
  261. }
  262. }
  263. /**
  264. * Checks if there are more entries.
  265. * @return true, iff there are more elements.
  266. */
  267. public boolean hasNext()
  268. {
  269. return nextEntry != null;
  270. }
  271. /**
  272. * Returns the next entry.
  273. * @return the next entry.
  274. * @throws ConcurrentModificationException if the hash map was
  275. * modified.
  276. * @throws NoSuchElementException if there is no entry.
  277. */
  278. public Object next()
  279. {
  280. checkMod();
  281. if (nextEntry == null)
  282. throw new NoSuchElementException();
  283. lastEntry = nextEntry;
  284. nextEntry = findNext(lastEntry);
  285. return lastEntry;
  286. }
  287. /**
  288. * Removes the last returned entry from this set. This will
  289. * also remove the bucket of the underlying weak hash map.
  290. * @throws ConcurrentModificationException if the hash map was
  291. * modified.
  292. * @throws IllegalStateException if <code>next()</code> was
  293. * never called or the element was already removed.
  294. */
  295. public void remove()
  296. {
  297. checkMod();
  298. if (lastEntry == null)
  299. throw new IllegalStateException();
  300. modCount++;
  301. internalRemove(lastEntry.getBucket());
  302. lastEntry = null;
  303. knownMod++;
  304. }
  305. };
  306. }
  307. }
  308. /**
  309. * A bucket is a weak reference to the key, that contains a strong
  310. * reference to the value, a pointer to the next bucket and its slot
  311. * number. <br>
  312. *
  313. * It would be cleaner to have a WeakReference as field, instead of
  314. * extending it, but if a weak reference gets cleared, we only get
  315. * the weak reference (by queue.poll) and wouldn't know where to
  316. * look for this reference in the hashtable, to remove that entry.
  317. *
  318. * @author Jochen Hoenicke
  319. */
  320. private static class WeakBucket<K, V> extends WeakReference<K>
  321. {
  322. /**
  323. * The value of this entry. The key is stored in the weak
  324. * reference that we extend.
  325. */
  326. V value;
  327. /**
  328. * The next bucket describing another entry that uses the same
  329. * slot.
  330. */
  331. WeakBucket<K, V> next;
  332. /**
  333. * The slot of this entry. This should be
  334. * <code>Math.abs(key.hashCode() % buckets.length)</code>.
  335. *
  336. * But since the key may be silently removed we have to remember
  337. * the slot number.
  338. *
  339. * If this bucket was removed the slot is -1. This marker will
  340. * prevent the bucket from being removed twice.
  341. */
  342. int slot;
  343. /**
  344. * Creates a new bucket for the given key/value pair and the specified
  345. * slot.
  346. * @param key the key
  347. * @param queue the queue the weak reference belongs to
  348. * @param value the value
  349. * @param slot the slot. This must match the slot where this bucket
  350. * will be enqueued.
  351. */
  352. public WeakBucket(K key, ReferenceQueue queue, V value,
  353. int slot)
  354. {
  355. super(key, queue);
  356. this.value = value;
  357. this.slot = slot;
  358. }
  359. /**
  360. * This class gives the <code>Entry</code> representation of the
  361. * current bucket. It also keeps a strong reference to the
  362. * key; bad things may happen otherwise.
  363. */
  364. class WeakEntry implements Map.Entry<K, V>
  365. {
  366. /**
  367. * The strong ref to the key.
  368. */
  369. K key;
  370. /**
  371. * Creates a new entry for the key.
  372. * @param key the key
  373. */
  374. public WeakEntry(K key)
  375. {
  376. this.key = key;
  377. }
  378. /**
  379. * Returns the underlying bucket.
  380. * @return the owning bucket
  381. */
  382. public WeakBucket getBucket()
  383. {
  384. return WeakBucket.this;
  385. }
  386. /**
  387. * Returns the key.
  388. * @return the key
  389. */
  390. public K getKey()
  391. {
  392. return key == NULL_KEY ? null : key;
  393. }
  394. /**
  395. * Returns the value.
  396. * @return the value
  397. */
  398. public V getValue()
  399. {
  400. return value;
  401. }
  402. /**
  403. * This changes the value. This change takes place in
  404. * the underlying hash map.
  405. * @param newVal the new value
  406. * @return the old value
  407. */
  408. public V setValue(V newVal)
  409. {
  410. V oldVal = value;
  411. value = newVal;
  412. return oldVal;
  413. }
  414. /**
  415. * The hashCode as specified in the Entry interface.
  416. * @return the hash code
  417. */
  418. public int hashCode()
  419. {
  420. return key.hashCode() ^ WeakHashMap.hashCode(value);
  421. }
  422. /**
  423. * The equals method as specified in the Entry interface.
  424. * @param o the object to compare to
  425. * @return true iff o represents the same key/value pair
  426. */
  427. public boolean equals(Object o)
  428. {
  429. if (o instanceof Map.Entry)
  430. {
  431. Map.Entry e = (Map.Entry) o;
  432. return WeakHashMap.equals(getKey(), e.getKey())
  433. && WeakHashMap.equals(value, e.getValue());
  434. }
  435. return false;
  436. }
  437. public String toString()
  438. {
  439. return getKey() + "=" + value;
  440. }
  441. }
  442. /**
  443. * This returns the entry stored in this bucket, or null, if the
  444. * bucket got cleared in the mean time.
  445. * @return the Entry for this bucket, if it exists
  446. */
  447. WeakEntry getEntry()
  448. {
  449. final K key = this.get();
  450. if (key == null)
  451. return null;
  452. return new WeakEntry(key);
  453. }
  454. }
  455. /**
  456. * The entry set returned by <code>entrySet()</code>.
  457. */
  458. private final WeakEntrySet theEntrySet;
  459. /**
  460. * The hash buckets. These are linked lists. Package visible for use in
  461. * nested classes.
  462. */
  463. WeakBucket[] buckets;
  464. /**
  465. * Creates a new weak hash map with default load factor and default
  466. * capacity.
  467. */
  468. public WeakHashMap()
  469. {
  470. this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR);
  471. }
  472. /**
  473. * Creates a new weak hash map with default load factor and the given
  474. * capacity.
  475. * @param initialCapacity the initial capacity
  476. * @throws IllegalArgumentException if initialCapacity is negative
  477. */
  478. public WeakHashMap(int initialCapacity)
  479. {
  480. this(initialCapacity, DEFAULT_LOAD_FACTOR);
  481. }
  482. /**
  483. * Creates a new weak hash map with the given initial capacity and
  484. * load factor.
  485. * @param initialCapacity the initial capacity.
  486. * @param loadFactor the load factor (see class description of HashMap).
  487. * @throws IllegalArgumentException if initialCapacity is negative, or
  488. * loadFactor is non-positive
  489. */
  490. public WeakHashMap(int initialCapacity, float loadFactor)
  491. {
  492. // Check loadFactor for NaN as well.
  493. if (initialCapacity < 0 || ! (loadFactor > 0))
  494. throw new IllegalArgumentException();
  495. if (initialCapacity == 0)
  496. initialCapacity = 1;
  497. this.loadFactor = loadFactor;
  498. threshold = (int) (initialCapacity * loadFactor);
  499. theEntrySet = new WeakEntrySet();
  500. queue = new ReferenceQueue();
  501. buckets = new WeakBucket[initialCapacity];
  502. }
  503. /**
  504. * Construct a new WeakHashMap with the same mappings as the given map.
  505. * The WeakHashMap has a default load factor of 0.75.
  506. *
  507. * @param m the map to copy
  508. * @throws NullPointerException if m is null
  509. * @since 1.3
  510. */
  511. public WeakHashMap(Map<? extends K, ? extends V> m)
  512. {
  513. this(m.size(), DEFAULT_LOAD_FACTOR);
  514. putAll(m);
  515. }
  516. /**
  517. * Simply hashes a non-null Object to its array index.
  518. * @param key the key to hash
  519. * @return its slot number
  520. */
  521. private int hash(Object key)
  522. {
  523. return Math.abs(key.hashCode() % buckets.length);
  524. }
  525. /**
  526. * Cleans the reference queue. This will poll all references (which
  527. * are WeakBuckets) from the queue and remove them from this map.
  528. * This will not change modCount, even if it modifies the map. The
  529. * iterators have to make sure that nothing bad happens. <br>
  530. *
  531. * Currently the iterator maintains a strong reference to the key, so
  532. * that is no problem.
  533. */
  534. // Package visible for use by nested classes.
  535. void cleanQueue()
  536. {
  537. Object bucket = queue.poll();
  538. while (bucket != null)
  539. {
  540. internalRemove((WeakBucket) bucket);
  541. bucket = queue.poll();
  542. }
  543. }
  544. /**
  545. * Rehashes this hashtable. This will be called by the
  546. * <code>add()</code> method if the size grows beyond the threshold.
  547. * It will grow the bucket size at least by factor two and allocates
  548. * new buckets.
  549. */
  550. private void rehash()
  551. {
  552. WeakBucket[] oldBuckets = buckets;
  553. int newsize = buckets.length * 2 + 1; // XXX should be prime.
  554. threshold = (int) (newsize * loadFactor);
  555. buckets = new WeakBucket[newsize];
  556. // Now we have to insert the buckets again.
  557. for (int i = 0; i < oldBuckets.length; i++)
  558. {
  559. WeakBucket bucket = oldBuckets[i];
  560. WeakBucket nextBucket;
  561. while (bucket != null)
  562. {
  563. nextBucket = bucket.next;
  564. Object key = bucket.get();
  565. if (key == null)
  566. {
  567. // This bucket should be removed; it is probably
  568. // already on the reference queue. We don't insert it
  569. // at all, and mark it as cleared.
  570. bucket.slot = -1;
  571. size--;
  572. }
  573. else
  574. {
  575. // Add this bucket to its new slot.
  576. int slot = hash(key);
  577. bucket.slot = slot;
  578. bucket.next = buckets[slot];
  579. buckets[slot] = bucket;
  580. }
  581. bucket = nextBucket;
  582. }
  583. }
  584. }
  585. /**
  586. * Finds the entry corresponding to key. Since it returns an Entry
  587. * it will also prevent the key from being removed under us.
  588. * @param key the key, may be null
  589. * @return The WeakBucket.WeakEntry or null, if the key wasn't found.
  590. */
  591. private WeakBucket.WeakEntry internalGet(Object key)
  592. {
  593. if (key == null)
  594. key = NULL_KEY;
  595. int slot = hash(key);
  596. WeakBucket bucket = buckets[slot];
  597. while (bucket != null)
  598. {
  599. WeakBucket.WeakEntry entry = bucket.getEntry();
  600. if (entry != null && equals(key, entry.key))
  601. return entry;
  602. bucket = bucket.next;
  603. }
  604. return null;
  605. }
  606. /**
  607. * Adds a new key/value pair to the hash map.
  608. * @param key the key. This mustn't exists in the map. It may be null.
  609. * @param value the value.
  610. */
  611. private void internalAdd(Object key, Object value)
  612. {
  613. if (key == null)
  614. key = NULL_KEY;
  615. int slot = hash(key);
  616. WeakBucket bucket = new WeakBucket(key, queue, value, slot);
  617. bucket.next = buckets[slot];
  618. buckets[slot] = bucket;
  619. size++;
  620. }
  621. /**
  622. * Removes a bucket from this hash map, if it wasn't removed before
  623. * (e.g. one time through rehashing and one time through reference queue).
  624. * Package visible for use in nested classes.
  625. *
  626. * @param bucket the bucket to remove.
  627. */
  628. void internalRemove(WeakBucket bucket)
  629. {
  630. int slot = bucket.slot;
  631. if (slot == -1)
  632. // This bucket was already removed.
  633. return;
  634. // Mark the bucket as removed. This is necessary, since the
  635. // bucket may be enqueued later by the garbage collection, and
  636. // internalRemove will be called a second time.
  637. bucket.slot = -1;
  638. WeakBucket prev = null;
  639. WeakBucket next = buckets[slot];
  640. while (next != bucket)
  641. {
  642. if (next == null) throw new InternalError("WeakHashMap in incosistent state");
  643. prev = next;
  644. next = prev.next;
  645. }
  646. if (prev == null)
  647. buckets[slot] = bucket.next;
  648. else
  649. prev.next = bucket.next;
  650. size--;
  651. }
  652. /**
  653. * Returns the size of this hash map. Note that the size() may shrink
  654. * spontaneously, if the some of the keys were only weakly reachable.
  655. * @return the number of entries in this hash map.
  656. */
  657. public int size()
  658. {
  659. cleanQueue();
  660. return size;
  661. }
  662. /**
  663. * Tells if the map is empty. Note that the result may change
  664. * spontanously, if all of the keys were only weakly reachable.
  665. * @return true, iff the map is empty.
  666. */
  667. public boolean isEmpty()
  668. {
  669. cleanQueue();
  670. return size == 0;
  671. }
  672. /**
  673. * Tells if the map contains the given key. Note that the result
  674. * may change spontanously, if the key was only weakly
  675. * reachable.
  676. * @param key the key to look for
  677. * @return true, iff the map contains an entry for the given key.
  678. */
  679. public boolean containsKey(Object key)
  680. {
  681. cleanQueue();
  682. return internalGet(key) != null;
  683. }
  684. /**
  685. * Gets the value the key is mapped to.
  686. * @return the value the key was mapped to. It returns null if
  687. * the key wasn't in this map, or if the mapped value was
  688. * explicitly set to null.
  689. */
  690. public V get(Object key)
  691. {
  692. cleanQueue();
  693. WeakBucket<K, V>.WeakEntry entry = internalGet(key);
  694. return entry == null ? null : entry.getValue();
  695. }
  696. /**
  697. * Adds a new key/value mapping to this map.
  698. * @param key the key, may be null
  699. * @param value the value, may be null
  700. * @return the value the key was mapped to previously. It returns
  701. * null if the key wasn't in this map, or if the mapped value
  702. * was explicitly set to null.
  703. */
  704. public V put(K key, V value)
  705. {
  706. cleanQueue();
  707. WeakBucket<K, V>.WeakEntry entry = internalGet(key);
  708. if (entry != null)
  709. return entry.setValue(value);
  710. modCount++;
  711. if (size >= threshold)
  712. rehash();
  713. internalAdd(key, value);
  714. return null;
  715. }
  716. /**
  717. * Removes the key and the corresponding value from this map.
  718. * @param key the key. This may be null.
  719. * @return the value the key was mapped to previously. It returns
  720. * null if the key wasn't in this map, or if the mapped value was
  721. * explicitly set to null.
  722. */
  723. public V remove(Object key)
  724. {
  725. cleanQueue();
  726. WeakBucket<K, V>.WeakEntry entry = internalGet(key);
  727. if (entry == null)
  728. return null;
  729. modCount++;
  730. internalRemove(entry.getBucket());
  731. return entry.getValue();
  732. }
  733. /**
  734. * Returns a set representation of the entries in this map. This
  735. * set will not have strong references to the keys, so they can be
  736. * silently removed. The returned set has therefore the same
  737. * strange behaviour (shrinking size(), disappearing entries) as
  738. * this weak hash map.
  739. * @return a set representation of the entries.
  740. */
  741. public Set<Map.Entry<K,V>> entrySet()
  742. {
  743. cleanQueue();
  744. return theEntrySet;
  745. }
  746. /**
  747. * Clears all entries from this map.
  748. */
  749. public void clear()
  750. {
  751. super.clear();
  752. }
  753. /**
  754. * Returns true if the map contains at least one key which points to
  755. * the specified object as a value. Note that the result
  756. * may change spontanously, if its key was only weakly reachable.
  757. * @param value the value to search for
  758. * @return true if it is found in the set.
  759. */
  760. public boolean containsValue(Object value)
  761. {
  762. cleanQueue();
  763. return super.containsValue(value);
  764. }
  765. /**
  766. * Returns a set representation of the keys in this map. This
  767. * set will not have strong references to the keys, so they can be
  768. * silently removed. The returned set has therefore the same
  769. * strange behaviour (shrinking size(), disappearing entries) as
  770. * this weak hash map.
  771. * @return a set representation of the keys.
  772. */
  773. public Set<K> keySet()
  774. {
  775. cleanQueue();
  776. return super.keySet();
  777. }
  778. /**
  779. * Puts all of the mappings from the given map into this one. If the
  780. * key already exists in this map, its value is replaced.
  781. * @param m the map to copy in
  782. */
  783. public void putAll(Map<? extends K, ? extends V> m)
  784. {
  785. super.putAll(m);
  786. }
  787. /**
  788. * Returns a collection representation of the values in this map. This
  789. * collection will not have strong references to the keys, so mappings
  790. * can be silently removed. The returned collection has therefore the same
  791. * strange behaviour (shrinking size(), disappearing entries) as
  792. * this weak hash map.
  793. * @return a collection representation of the values.
  794. */
  795. public Collection<V> values()
  796. {
  797. cleanQueue();
  798. return super.values();
  799. }
  800. } // class WeakHashMap