Search code examples
javamultithreadingconcurrenthashmapcallable

How to store Java Callable job in ConcurrentHashMap


I am new to the Multithreading and here is a question: For a Callable interface, like:

public interface Callable<V> {
    public V call();
}

Now I need to implement a class with three method:

/* register some callable jobs with the signal key */
void register(int signal, Callable cb); 

/* unregister */
void unregister(int signal, Callable cb);

/* run all the jobs with the given signal */
void signal(int signal);

I am thinking the register and unregister function I will use a ConcurrentHashMap in java, some structure like :

ConcurrentHashMap<Integer, List<Callable>> 

Then here are my questions:

  1. how to support the above three method? How to pass a Callable as a variable? The void signal(int signal) will run all the callable with the given signal key.
  2. for Callable interface, need to implement the V call() function. How does this call() relate to the signal() method? Should signal call this call()?

Solution

  • You can create new iterface extends callable and add your custom method like getId.

     public interface  MyCallable  extends Callable<String> {
      public int getId();
    }
    

    -Create a implemented class which will implement your custom callable interface.

     public class CallableImpl implements Callable<String> {
           private Callable action;
           private int key;
         public CallableImpl (Callable action,int key){
              this.action=action;
              this.key=key;
            }
            @Override
            public String call() throws Exception {
              return  action.call();
            }
        public int getId(){
         return key;
    }
    

    -register(int signal, Callable cb) method will take the object of callable class and store in a hashmap.On call to void signal(int signal) it will collect all list of action from hashmap and submit to an executor.

    ExecutorService executor = Executors.newFixedThreadPool(10);
    void signal(int signal){
    for(Callable c:actionList){
      //submit Callable tasks to be executed by thread pool
      Future<String> future = executor.submit(callable);
      //add Future to the list, we can get return value using Future
      list.add(future);
    }
    }