Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why java class WeakReference does not override hashcode and equals

I was expecting the WeakReference class to override hashCode and equals methods like this

class WeakReference<T>{
  T ref;

  int hashCode(){
    return ref.hashCode();
  }

  boolean equals(Object o){
    return ref.equals(o);
  }
}

So that I could use We WeakReference directly as key in hashmaps like

Person p1 = new Person("p1");
WeakReference<Person> wr = new WeakReference<Person>(p1);

map.put(wr, "some value object");

But when I tested I found out that hashCode and equals are not overridden

Person p1 = new Person("p1");
WeakReference<Person> wr = new WeakReference<Person>(p1);
WeakReference<Person> wr2 = new WeakReference<Person>(p1);

System.out.println(wr.hashCode()); // prints x
System.out.println(wr2.hashCode()); // prints y

System.out.println(wr.equals(wr2)); // prints false

Any specific reasons reasons that hashCode and equals are not overridden in WeakReference class?

like image 752
Mangoose Avatar asked Jul 20 '26 21:07

Mangoose


1 Answers

An important aspect of any key on a Map (or element of a Set) is that it must be immutable (or at least not change) once it has been added to the collection. Changing a key has undefined behaviour which is highly unlikely to work.

A WeakReference can change at any time due to a GC being performed i.e. in ways you have no control over, which makes the equals/hashCode inappropriate for general collections which use these.

I was trying to make MyWeakConcurrentHashMap

A simple way of doing this is to have an array of WeakHashMaps. e.g. 32 partitions . Use the hashCode() to determine which WeakHashMap to use. This way you can have a thread accessing each of the individual WeakHashMap at once (best case)

As you have more concurrency you can increase the number of partitions.

like image 198
Peter Lawrey Avatar answered Jul 22 '26 10:07

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!