We usually use IDE to override equals and hashCode methods in our classes.
Let's see how IntelliJ IDEA 11 copes with a simple class with 3 fields:
Even though the class seems simple, the methods' size is a little bit scary.
Using EqualsBuilder and HashCodeBuilder from Apache Commons Lang makes the methods much smaller, however introduces one major flaw: it uses reflection, which isn't a speed demon.
To the rescue comes Guava, which makes these methods simpler and more readable:
If you're working on a project in which you can use Java 7, it provides a similar solution without having to use any external library:
At the time of writing this, IDEA 11 doesn't support generating equals and hashCode using Guava or Objects class from Java 7. I created a plugin that provides such possibility:
http://plugins.intellij.net/plugin/?idea&id=6875
Showing posts with label guava. Show all posts
Showing posts with label guava. Show all posts
Friday, 24 February 2012
Sunday, 12 February 2012
Concurrent map with timed out elements using Guava library
Sometimes we have a need to use a map, in which elements live only for a specified amount of time.
We could implement such map ourselves (by overriding removeEldestEntry() from LinkedHashMap or using thread that will be removing elements periodically) but the better idea is to use already existing implementation. Google's guava library (http://code.google.com/p/guava-libraries) is the solution for us.
Let's write some simple unit tests to check the API and verify behaviour:
Map is created using the builder pattern. Apart from specifying the time of elements expiration, it allows among others, setting the maximum map's size or the listener that will be notified each time an entry is removed. As the built object is an instance of Cache, we need to create ConcurrentMap from it using asMap() method.
Two tests verify that added element is removed only when the timeout expires.
We could implement such map ourselves (by overriding removeEldestEntry() from LinkedHashMap or using thread that will be removing elements periodically) but the better idea is to use already existing implementation. Google's guava library (http://code.google.com/p/guava-libraries) is the solution for us.
Let's write some simple unit tests to check the API and verify behaviour:
Map is created using the builder pattern. Apart from specifying the time of elements expiration, it allows among others, setting the maximum map's size or the listener that will be notified each time an entry is removed. As the built object is an instance of Cache, we need to create ConcurrentMap from it using asMap() method.
Two tests verify that added element is removed only when the timeout expires.
Subscribe to:
Posts (Atom)