/**
* IdentifyHashMap -
* - Implements Map Interface with a hash table using reference-equality instead of object-equality when comparing keys.
* Eg: if ( k1 == k2 ) unlike HashMap equality if( K1 == null ? k2 ==null : k1.equals(k2)).
* - It's not a general purpose implementation and designed to use only in rare cases where reference-equality semantics are required
* - Use cases like topology-preserving object graph, deep-copying, adding application shutdown hook.
* - This Map is not synchronized. To synchronize use Collections SynchronizedMap
* Map identifyHashMap = Collections.synchronizedMap( new IdentifyHashMap(..)) ;
*
*/
import java.util.Collection;
import java.util.IdentityHashMap;
public class ApplicationDaemons
{
private static IdentityHashMap<Thread, Thread> applicationdaemons = new IdentityHashMap<>();
public synchronized void runDaemonsInSeperateThread() {
new Runnable()
{
public void run()
{
runDaemons() ;
}
} ;
}
private ApplicationDaemons() {}
static synchronized void add(Thread hook) {
if(applicationdaemons != null)
applicationdaemons.put(hook, hook);
}
static synchronized boolean remove(Thread hook) {
return applicationdaemons.remove(hook) != null;
}
static void runDaemons() {
Collection<Thread> threads;
synchronized(ApplicationDaemons.class) {
threads = applicationdaemons.keySet();
applicationdaemons = null;
}
for (Thread hook : threads) {
hook.start();
}
for (Thread hook : threads) {
try {
hook.join();
} catch (InterruptedException x) { }
}
}
}
No comments:
Post a Comment