Last active
May 11, 2018 08:54
-
-
Save oxbowlakes/6375592 to your computer and use it in GitHub Desktop.
Concurrency interview question
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/////////////////////////////////////////////////////////////////////// | |
// You are supplied with the following interfaces/implementations | |
/////////////////////////////////////////////////////////////////////// | |
/** Interface representing the performing of a computation at some specific key */ | |
public interface Computation<K, V> { | |
K key(); | |
V compute(); | |
} | |
/** Concurrent data structure */ | |
public class ConcMap<K, V> { | |
/** | |
* If a mapping exists at a given key, return it. Otherwise add the new mapping and return null. This operation is threadsafe | |
* and ConcMap guarantees that only one thread can ever successfully add a mapping at any given key | |
*/ | |
public V putIfAbsent(K k, V v) { /* implementation */ } | |
} | |
/** Interface representing a value which will be present at some point in time */ | |
public interface Promise<T> { | |
/** | |
* Return the value (waiting for it to become available, if necessary, by blocking the current thread of execution) | |
*/ | |
T value(); | |
} | |
/** Thunk is an implementation of the Promise interface, which takes a Computation from which to | |
* compute its value. Note that the Thunk is non-strict, in that the computation is not performed on construction | |
*/ | |
public class Thunk<T> implements Promise<T> { | |
/** | |
* Construct a Thunk which, when run is called, will take its value from the supplied computation | |
*/ | |
public Thunk(Computation<?, T> c) { /* implementation */ } | |
/** | |
* Cause this Thunk's value to be set, by running the computation in the current thread. | |
* Once the value of this Thunk is set, subsequent calls to run are no-ops. | |
*/ | |
public void run() { /* implementation */ } | |
public T value() { /* implementation */ } | |
} | |
/////////////////////////////////////////////////////////////////////// | |
// use these data structures to implement the following "concurrent" cache | |
/////////////////////////////////////////////////////////////////////// | |
public class ConcCache<K, V> { | |
/** | |
* Return the value for the supplied computation. Exactly one thread should perform the computation for any given key | |
*/ | |
public V get(Computation<K, V> c); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment