HashMap
is non-synchronized in Java. So to perform thread-safe operations,you
must synchronize HashMap.
There
are two ways.
1. Synchronizing
the map explicitly.
2. Use
'Collections.synchronizedMap' method.
import java.util.*; public class MapEx { public static void main(String args[]){ Map<Integer, Integer> map = Collections.synchronizedMap(new HashMap<>()); map.put(1, 1*1); map.put(2, 2*2); map.put(3, 3*3); System.out.println(map); } }
Output
{1=1, 2=4, 3=9}
No comments:
Post a Comment