Search code examples
javahashmaphashtablejava.util.concurrent

Insertion of null value in a ConcurrentSkipListMap Java


I know it's maybe not the best thing to do and that I'm not using properly this object, but here is my problem. I want to use a ConcurrentSkipListMap and have declared my map as such:

private ConcurrentSkipListMap<Date,T> map 

Sometimes, I need to initialize elements of this map with a "null" value, meaning that on a given day, there were no data. For a regular hastable, that works, you can insert a null value associated to a key. When getting the value for a certain date, I just have to test if it is null or not. For a ConcurrentSkipListMap, that does not work. It throws a null value exception. When looking at the source code, I understood that this is an internal representation of the Nodes where a null value just means that the Node in the list is dead.

I know the best answer to this would be, just don't add the date in that case... but for many reasons, I still need to. And anyway, testing for the existence of the key is to me the same as testing for a null value associated to a key. I can't add a dummy value as well cause I will not be able to make a distinction between this dummy value and a real one (for, example, if my template class is an Integer, even if I choose -1 as a flag for empty, i would not be able to see the difference with a real value of -1 for this day).

I was previously using

private SortedMap<Date,T> map = Collections.synchronizedSortedMap(new TreeMap<Date,T>(new BasicDateComparatorIncreasing()));

but I like the fact that ConcurentSkipListMap implements the ConcurrentNavigableMap interface

Is there a way to achieve what I want to do ?

thanks


Solution

  • How about

    private ConcurrentSkipListMap<Optional<Date>, T> map;
    

    ?

    Then to add elements:

    map.put(Optional.fromNullable(date), value);
    

    And when accessing key check Optional.isPresent() and call Optional.get().

    http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Optional.html