WeakHashMap.java 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  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 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., 59 Temple Place, Suite 330, Boston, MA
  16. 02111-1307 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.WeakReference;
  34. import java.lang.ref.ReferenceQueue;
  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. *
  71. * @see HashMap
  72. * @see WeakReference
  73. * @see LinkedHashMap
  74. * @since 1.2
  75. * @status updated to 1.4
  76. */
  77. public class WeakHashMap extends AbstractMap implements Map
  78. {
  79. // WARNING: WeakHashMap is a CORE class in the bootstrap cycle. See the
  80. // comments in vm/reference/java/lang/Runtime for implications of this fact.
  81. /**
  82. * The default capacity for an instance of HashMap.
  83. * Sun's documentation mildly suggests that this (11) is the correct
  84. * value.
  85. */
  86. private static final int DEFAULT_CAPACITY = 11;
  87. /**
  88. * The default load factor of a HashMap.
  89. */
  90. private static final float DEFAULT_LOAD_FACTOR = 0.75F;
  91. /**
  92. * This is used instead of the key value <i>null</i>. It is needed
  93. * to distinguish between an null key and a removed key.
  94. */
  95. // Package visible for use by nested classes.
  96. static final Object NULL_KEY = new Object()
  97. {
  98. /**
  99. * Sets the hashCode to 0, since that's what null would map to.
  100. * @return the hash code 0
  101. */
  102. public int hashCode()
  103. {
  104. return 0;
  105. }
  106. /**
  107. * Compares this key to the given object. Normally, an object should
  108. * NEVER compare equal to null, but since we don't publicize NULL_VALUE,
  109. * it saves bytecode to do so here.
  110. * @return true iff o is this or null
  111. */
  112. public boolean equals(Object o)
  113. {
  114. return null == o || this == o;
  115. }
  116. };
  117. /**
  118. * The reference queue where our buckets (which are WeakReferences) are
  119. * registered to.
  120. */
  121. private final ReferenceQueue queue;
  122. /**
  123. * The number of entries in this hash map.
  124. */
  125. // Package visible for use by nested classes.
  126. int size;
  127. /**
  128. * The load factor of this WeakHashMap. This is the maximum ratio of
  129. * size versus number of buckets. If size grows the number of buckets
  130. * must grow, too.
  131. */
  132. private float loadFactor;
  133. /**
  134. * The rounded product of the capacity (i.e. number of buckets) and
  135. * the load factor. When the number of elements exceeds the
  136. * threshold, the HashMap calls <code>rehash()</code>.
  137. */
  138. private int threshold;
  139. /**
  140. * The number of structural modifications. This is used by
  141. * iterators, to see if they should fail. This doesn't count
  142. * the silent key removals, when a weak reference is cleared
  143. * by the garbage collection. Instead the iterators must make
  144. * sure to have strong references to the entries they rely on.
  145. */
  146. // Package visible for use by nested classes.
  147. int modCount;
  148. /**
  149. * The entry set. There is only one instance per hashmap, namely
  150. * theEntrySet. Note that the entry set may silently shrink, just
  151. * like the WeakHashMap.
  152. */
  153. private final class WeakEntrySet extends AbstractSet
  154. {
  155. /**
  156. * Non-private constructor to reduce bytecode emitted.
  157. */
  158. WeakEntrySet()
  159. {
  160. }
  161. /**
  162. * Returns the size of this set.
  163. *
  164. * @return the set size
  165. */
  166. public int size()
  167. {
  168. return size;
  169. }
  170. /**
  171. * Returns an iterator for all entries.
  172. *
  173. * @return an Entry iterator
  174. */
  175. public Iterator iterator()
  176. {
  177. return new Iterator()
  178. {
  179. /**
  180. * The entry that was returned by the last
  181. * <code>next()</code> call. This is also the entry whose
  182. * bucket should be removed by the <code>remove</code> call. <br>
  183. *
  184. * It is null, if the <code>next</code> method wasn't
  185. * called yet, or if the entry was already removed. <br>
  186. *
  187. * Remembering this entry here will also prevent it from
  188. * being removed under us, since the entry strongly refers
  189. * to the key.
  190. */
  191. WeakBucket.WeakEntry lastEntry;
  192. /**
  193. * The entry that will be returned by the next
  194. * <code>next()</code> call. It is <code>null</code> if there
  195. * is no further entry. <br>
  196. *
  197. * Remembering this entry here will also prevent it from
  198. * being removed under us, since the entry strongly refers
  199. * to the key.
  200. */
  201. WeakBucket.WeakEntry nextEntry = findNext(null);
  202. /**
  203. * The known number of modification to the list, if it differs
  204. * from the real number, we throw an exception.
  205. */
  206. int knownMod = modCount;
  207. /**
  208. * Check the known number of modification to the number of
  209. * modifications of the table. If it differs from the real
  210. * number, we throw an exception.
  211. * @throws ConcurrentModificationException if the number
  212. * of modifications doesn't match.
  213. */
  214. private void checkMod()
  215. {
  216. // This method will get inlined.
  217. cleanQueue();
  218. if (knownMod != modCount)
  219. throw new ConcurrentModificationException();
  220. }
  221. /**
  222. * Get a strong reference to the next entry after
  223. * lastBucket.
  224. * @param lastEntry the previous bucket, or null if we should
  225. * get the first entry.
  226. * @return the next entry.
  227. */
  228. private WeakBucket.WeakEntry findNext(WeakBucket.WeakEntry lastEntry)
  229. {
  230. int slot;
  231. WeakBucket nextBucket;
  232. if (lastEntry != null)
  233. {
  234. nextBucket = lastEntry.getBucket().next;
  235. slot = lastEntry.getBucket().slot;
  236. }
  237. else
  238. {
  239. nextBucket = buckets[0];
  240. slot = 0;
  241. }
  242. while (true)
  243. {
  244. while (nextBucket != null)
  245. {
  246. WeakBucket.WeakEntry entry = nextBucket.getEntry();
  247. if (entry != null)
  248. // This is the next entry.
  249. return entry;
  250. // Entry was cleared, try next.
  251. nextBucket = nextBucket.next;
  252. }
  253. slot++;
  254. if (slot == buckets.length)
  255. // No more buckets, we are through.
  256. return null;
  257. nextBucket = buckets[slot];
  258. }
  259. }
  260. /**
  261. * Checks if there are more entries.
  262. * @return true, iff there are more elements.
  263. * @throws ConcurrentModificationException if the hash map was
  264. * modified.
  265. */
  266. public boolean hasNext()
  267. {
  268. checkMod();
  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 extends WeakReference
  321. {
  322. /**
  323. * The value of this entry. The key is stored in the weak
  324. * reference that we extend.
  325. */
  326. Object value;
  327. /**
  328. * The next bucket describing another entry that uses the same
  329. * slot.
  330. */
  331. WeakBucket 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(Object key, ReferenceQueue queue, Object 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
  365. {
  366. /**
  367. * The strong ref to the key.
  368. */
  369. Object key;
  370. /**
  371. * Creates a new entry for the key.
  372. * @param key the key
  373. */
  374. public WeakEntry(Object 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 Object getKey()
  391. {
  392. return key == NULL_KEY ? null : key;
  393. }
  394. /**
  395. * Returns the value.
  396. * @return the value
  397. */
  398. public Object 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 Object setValue(Object newVal)
  409. {
  410. Object 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 key.equals(e.getKey())
  433. && WeakHashMap.equals(value, e.getValue());
  434. }
  435. return false;
  436. }
  437. public String toString()
  438. {
  439. return key + "=" + 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 Object 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. this.loadFactor = loadFactor;
  496. threshold = (int) (initialCapacity * loadFactor);
  497. theEntrySet = new WeakEntrySet();
  498. queue = new ReferenceQueue();
  499. buckets = new WeakBucket[initialCapacity];
  500. }
  501. /**
  502. * Construct a new WeakHashMap with the same mappings as the given map.
  503. * The WeakHashMap has a default load factor of 0.75.
  504. *
  505. * @param m the map to copy
  506. * @throws NullPointerException if m is null
  507. * @since 1.3
  508. */
  509. public WeakHashMap(Map m)
  510. {
  511. this(m.size(), DEFAULT_LOAD_FACTOR);
  512. putAll(m);
  513. }
  514. /**
  515. * Simply hashes a non-null Object to its array index.
  516. * @param key the key to hash
  517. * @return its slot number
  518. */
  519. private int hash(Object key)
  520. {
  521. return Math.abs(key.hashCode() % buckets.length);
  522. }
  523. /**
  524. * Cleans the reference queue. This will poll all references (which
  525. * are WeakBuckets) from the queue and remove them from this map.
  526. * This will not change modCount, even if it modifies the map. The
  527. * iterators have to make sure that nothing bad happens. <br>
  528. *
  529. * Currently the iterator maintains a strong reference to the key, so
  530. * that is no problem.
  531. */
  532. // Package visible for use by nested classes.
  533. void cleanQueue()
  534. {
  535. Object bucket = queue.poll();
  536. while (bucket != null)
  537. {
  538. internalRemove((WeakBucket) bucket);
  539. bucket = queue.poll();
  540. }
  541. }
  542. /**
  543. * Rehashes this hashtable. This will be called by the
  544. * <code>add()</code> method if the size grows beyond the threshold.
  545. * It will grow the bucket size at least by factor two and allocates
  546. * new buckets.
  547. */
  548. private void rehash()
  549. {
  550. WeakBucket[] oldBuckets = buckets;
  551. int newsize = buckets.length * 2 + 1; // XXX should be prime.
  552. threshold = (int) (newsize * loadFactor);
  553. buckets = new WeakBucket[newsize];
  554. // Now we have to insert the buckets again.
  555. for (int i = 0; i < oldBuckets.length; i++)
  556. {
  557. WeakBucket bucket = oldBuckets[i];
  558. WeakBucket nextBucket;
  559. while (bucket != null)
  560. {
  561. nextBucket = bucket.next;
  562. Object key = bucket.get();
  563. if (key == null)
  564. {
  565. // This bucket should be removed; it is probably
  566. // already on the reference queue. We don't insert it
  567. // at all, and mark it as cleared.
  568. bucket.slot = -1;
  569. size--;
  570. }
  571. else
  572. {
  573. // Add this bucket to its new slot.
  574. int slot = hash(key);
  575. bucket.slot = slot;
  576. bucket.next = buckets[slot];
  577. buckets[slot] = bucket;
  578. }
  579. bucket = nextBucket;
  580. }
  581. }
  582. }
  583. /**
  584. * Finds the entry corresponding to key. Since it returns an Entry
  585. * it will also prevent the key from being removed under us.
  586. * @param key the key, may be null
  587. * @return The WeakBucket.WeakEntry or null, if the key wasn't found.
  588. */
  589. private WeakBucket.WeakEntry internalGet(Object key)
  590. {
  591. if (key == null)
  592. key = NULL_KEY;
  593. int slot = hash(key);
  594. WeakBucket bucket = buckets[slot];
  595. while (bucket != null)
  596. {
  597. WeakBucket.WeakEntry entry = bucket.getEntry();
  598. if (entry != null && key.equals(entry.key))
  599. return entry;
  600. bucket = bucket.next;
  601. }
  602. return null;
  603. }
  604. /**
  605. * Adds a new key/value pair to the hash map.
  606. * @param key the key. This mustn't exists in the map. It may be null.
  607. * @param value the value.
  608. */
  609. private void internalAdd(Object key, Object value)
  610. {
  611. if (key == null)
  612. key = NULL_KEY;
  613. int slot = hash(key);
  614. WeakBucket bucket = new WeakBucket(key, queue, value, slot);
  615. bucket.next = buckets[slot];
  616. buckets[slot] = bucket;
  617. size++;
  618. }
  619. /**
  620. * Removes a bucket from this hash map, if it wasn't removed before
  621. * (e.g. one time through rehashing and one time through reference queue).
  622. * Package visible for use in nested classes.
  623. *
  624. * @param bucket the bucket to remove.
  625. */
  626. void internalRemove(WeakBucket bucket)
  627. {
  628. int slot = bucket.slot;
  629. if (slot == -1)
  630. // This bucket was already removed.
  631. return;
  632. // Mark the bucket as removed. This is necessary, since the
  633. // bucket may be enqueued later by the garbage collection, and
  634. // internalRemove will be called a second time.
  635. bucket.slot = -1;
  636. if (buckets[slot] == bucket)
  637. buckets[slot] = bucket.next;
  638. else
  639. {
  640. WeakBucket prev = buckets[slot];
  641. /* This may throw a NullPointerException. It shouldn't but if
  642. * a race condition occurred (two threads removing the same
  643. * bucket at the same time) it may happen. <br>
  644. * But with race condition many much worse things may happen
  645. * anyway.
  646. */
  647. while (prev.next != bucket)
  648. prev = prev.next;
  649. prev.next = bucket.next;
  650. }
  651. size--;
  652. }
  653. /**
  654. * Returns the size of this hash map. Note that the size() may shrink
  655. * spontaneously, if the some of the keys were only weakly reachable.
  656. * @return the number of entries in this hash map.
  657. */
  658. public int size()
  659. {
  660. cleanQueue();
  661. return size;
  662. }
  663. /**
  664. * Tells if the map is empty. Note that the result may change
  665. * spontanously, if all of the keys were only weakly reachable.
  666. * @return true, iff the map is empty.
  667. */
  668. public boolean isEmpty()
  669. {
  670. cleanQueue();
  671. return size == 0;
  672. }
  673. /**
  674. * Tells if the map contains the given key. Note that the result
  675. * may change spontanously, if the key was only weakly
  676. * reachable.
  677. * @param key the key to look for
  678. * @return true, iff the map contains an entry for the given key.
  679. */
  680. public boolean containsKey(Object key)
  681. {
  682. cleanQueue();
  683. return internalGet(key) != null;
  684. }
  685. /**
  686. * Gets the value the key is mapped to.
  687. * @return the value the key was mapped to. It returns null if
  688. * the key wasn't in this map, or if the mapped value was
  689. * explicitly set to null.
  690. */
  691. public Object get(Object key)
  692. {
  693. cleanQueue();
  694. WeakBucket.WeakEntry entry = internalGet(key);
  695. return entry == null ? null : entry.getValue();
  696. }
  697. /**
  698. * Adds a new key/value mapping to this map.
  699. * @param key the key, may be null
  700. * @param value the value, may be null
  701. * @return the value the key was mapped to previously. It returns
  702. * null if the key wasn't in this map, or if the mapped value
  703. * was explicitly set to null.
  704. */
  705. public Object put(Object key, Object value)
  706. {
  707. cleanQueue();
  708. WeakBucket.WeakEntry entry = internalGet(key);
  709. if (entry != null)
  710. return entry.setValue(value);
  711. modCount++;
  712. if (size >= threshold)
  713. rehash();
  714. internalAdd(key, value);
  715. return null;
  716. }
  717. /**
  718. * Removes the key and the corresponding value from this map.
  719. * @param key the key. This may be null.
  720. * @return the value the key was mapped to previously. It returns
  721. * null if the key wasn't in this map, or if the mapped value was
  722. * explicitly set to null.
  723. */
  724. public Object remove(Object key)
  725. {
  726. cleanQueue();
  727. WeakBucket.WeakEntry entry = internalGet(key);
  728. if (entry == null)
  729. return null;
  730. modCount++;
  731. internalRemove(entry.getBucket());
  732. return entry.getValue();
  733. }
  734. /**
  735. * Returns a set representation of the entries in this map. This
  736. * set will not have strong references to the keys, so they can be
  737. * silently removed. The returned set has therefore the same
  738. * strange behaviour (shrinking size(), disappearing entries) as
  739. * this weak hash map.
  740. * @return a set representation of the entries.
  741. */
  742. public Set entrySet()
  743. {
  744. cleanQueue();
  745. return theEntrySet;
  746. }
  747. /**
  748. * Clears all entries from this map.
  749. */
  750. public void clear()
  751. {
  752. super.clear();
  753. }
  754. /**
  755. * Returns true if the map contains at least one key which points to
  756. * the specified object as a value. Note that the result
  757. * may change spontanously, if its key was only weakly reachable.
  758. * @param value the value to search for
  759. * @return true if it is found in the set.
  760. */
  761. public boolean containsValue(Object value)
  762. {
  763. cleanQueue();
  764. return super.containsValue(value);
  765. }
  766. /**
  767. * Returns a set representation of the keys in this map. This
  768. * set will not have strong references to the keys, so they can be
  769. * silently removed. The returned set has therefore the same
  770. * strange behaviour (shrinking size(), disappearing entries) as
  771. * this weak hash map.
  772. * @return a set representation of the keys.
  773. */
  774. public Set keySet()
  775. {
  776. cleanQueue();
  777. return super.keySet();
  778. }
  779. /**
  780. * Puts all of the mappings from the given map into this one. If the
  781. * key already exists in this map, its value is replaced.
  782. * @param m the map to copy in
  783. */
  784. public void putAll(Map m)
  785. {
  786. super.putAll(m);
  787. }
  788. /**
  789. * Returns a collection representation of the values in this map. This
  790. * collection will not have strong references to the keys, so mappings
  791. * can be silently removed. The returned collection has therefore the same
  792. * strange behaviour (shrinking size(), disappearing entries) as
  793. * this weak hash map.
  794. * @return a collection representation of the values.
  795. */
  796. public Collection values()
  797. {
  798. cleanQueue();
  799. return super.values();
  800. }
  801. } // class WeakHashMap