Search code examples
javamultithreadingconcurrenthashmap

How do you figure out which thread will run first?


I have this exercise, but I don't understand the reason of the correct answer:

 import java.util.Iterator; 
    import java.util.Map.Entry; 
    import java.util.concurrent.ConcurrentHashMap; 

    public class Cache {          
    static ConcurrentHashMap<String, Object> chm = new ConcurrentHashMap<String, Object>();          
    public static void main(String[] args) {         
            chm.put("a", "aaa");         
            chm.put("b", "bbb");         
            chm.put("c", "ccc");                  
            new Thread(){             
                public void run(){                 
                    Iterator<Entry<String, Object>> it = Cache.chm.entrySet().iterator();                 
                    while(it.hasNext()){                     
                        Entry<String, Object> en = it.next();                     
                        if(en.getKey().equals("a") || en.getKey().equals("b")){                         
                            it.remove();                
                        }                 
                    }    
                }         
            }.start();                  

            new Thread(){             
                public void run(){                 
                    Iterator<Entry<String, Object>> it = Cache.chm.entrySet().iterator();                 
                    while(it.hasNext()){                     
                        Entry<String, Object> en = it.next();                     
                        System.out.print(en.getKey()+", ");                 
                    }             
                }         
            }.start();             
    } 
}

There were 4 possible answers:

  1. It may print any combination of the keys.
  2. It may print any combination except: c,
  3. It may print any combination except: a, or b, or a, b, or b, a
  4. It may print any combination except: b, c,

The correct answer for this exercise is 3.

Why this is the correct answer?

I thought this exercise may print any combination of the keys, because there are two thread in this main, so I don't know which of the both will start for first. If the second thread will start for first, I will have all the keys in the ConcurrentHashMap, so it will print a and b. So, my answer for this exercise was 1. But the exercise considers it as wrong answer. Why?

How do I figure out which thread will start for first?

Thanks a lot!

A.


Solution

  • There is no way to determine in advance which thread will start first beside you create one first.

    It only depends on the Scheduler which is part of the JVM. It does Threads management.

    If you want to wait to the first thread and then start the second you can easily use firstThread.join() and then start the second thread.