1

If two threads try to put (key, value) in same map passed in constructor of thread. What kind of threading issues i might encounter?

public class App {
    public static void main(String[] args) throws JMSException {
        Map<String, String> map = new HashMap<String, String>();
        map.put("5", "fnc");

        Thread t1 = new App().new T(map);
        Thread t2 = new App().new T(map);
        t1.start();
        t2.start();
    }

    class T extends Thread {

        private Map<String, String> map;

        public T(Map<String, String> map) {
            this.map = map;
        }

        public void run() {
            // put 100s of keys in map here
            map.put("1", "abc");
            // put other keys
        }
    }
}
Tarun Kumar
  • 5,150
  • 6
  • 26
  • 30
  • Concurrent reads and writes to the Oracle HashMap implementation can cause hung threads (pretty easy to get it into an infinite loop, due to the underlying implementation.) See http://stackoverflow.com/a/1068213/83695 – andersoj Mar 01 '14 at 04:20

2 Answers2

0

map will not be thread safe. that means few scenario shall happen

1) thread 1 trying to retrieve a entry from a key and thread 2 trying to modify the entry on that moment. 2) vice versa.

you can use ConcurrentHashMap to serve this purposes which handle concurrency.

java seeker
  • 1,246
  • 10
  • 13
0

One example: while thread 1 is putting a value, thread 2 decides to increase hash table capacity. In this case thread 1 may put its value to the old hash table and thread 2 may overwrite this hash table with a new one. Thread 1 put is lost.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275