An Interview Question

Given the following:

// ReadOnlyMap.java
public interface ReadOnlyMap<K, V> {        
    V get(K key);
}

// ReadWriteMap.java
public interface ReadWriteMap<K, V> {
    V get(K key);
    V put(K key, V value);
}

// MapFactory.java
public interface MapFactory {
    ReadOnlyMap<K, V> createReadOnlyMap(java.util.Map<K, V> map);
    ReadWriteMap<K, V> createReadWriteMap(java.util.Map<K, V> map);
}

Provide thread-safe implementations of ReadOnlyMap & ReadWriteMap and an implementation of MapFactory to create instances of these custom maps.

Bonus question: provide an implementation of ReadWriteMap optimized for read dominated workloads.

There is no single right answer. Just like there is no single wrong answer!

I think the above will work as a decent interview question for intermediate level Java developers. Agree or Disagree?

Comments

Should be fairly easy and a good way of knowing if the candidate knows the language. I don't know Java multithreading all that well; but I'm guessing you could do this either using synchronized methods or using a thread-safe container as the backend.

A slightly harder bonus question would be to ask how do you handle iterators in a thread-safe container environment.

Synchronizing everything or using a thread-safe backing container is one way to do it. And a beginner should be able to do that.

The trick is knowing how little synchronization can you get away with without sacrificing thread-safety. For example, ReadOnlyMap as specified above can be implemented entirely without any locking or synchronization! But knowing how to do it correctly requires a decent understanding of the Java Memory Model & the guarantees it provides about atomicity and visibility. That's what I would be looking for in an intermediate level developer.

Thread-safe iterators: that's definitely the harder one and is best left to the experts ;-)

The minimum answer should be: ReadOnlyMap requires no synchronization, ReadWriteMap can be implemented by making all public methods "synchronized", and the optimization is done by using a reader/writer lock. This will work as long as keys and values have value semantics. This is the basic level of knowledge that every programmer should be familiar with. An advanced programmer should be able to discuss finer issues.

Very well put Mr Milewski!


Markdown formatting supported