concurrency - Inconsistent HashMap between classes - Java -


I have a square, which has a hashmap as a public field:

  Public stable final hashmap < String, string & gt; Map = new hashmap & lt; String, string & gt; ();   

And in class B (which is multi-threaded, applying runnabble), I put something.

Now, from class I want to read the map. But the changes in the map are class C. Are not reflected in.

I do not store any reference anywhere, but I use the map through the name of the class.

  A map.put ("Hello", "hello"); // Thread B. A.map.get ("hi"); // in Thread C   

and I'm sure that I get calls after calling () ..

I thought there could be a problem with concurrency And I have changed the Hashmap to Hashbabel, but it is still the same ..

I repeated this problem as short code as possible

  Public Sector A {Public Static Last Hashmap & lt; String, string & gt; Map = new hashmap & lt; String, string & gt; (); Public static zero main (string [] args) {while (true); }} Public square b {public static zero main (string [] args) {scanner sc = new scanner (System.in); While (true) {string s = sc.nextLine (); A.map.put (s, "true"); Println (A.map.size ()); }}} Public class C {public static zero main (string [] args) {scanner sc = new scanner (System.in); While (true) {sc.nextLine (); Println (A.map.size ()); }}}   

I can see the growing size in print in class B, but C is always zero in size

Am I missing something here ?

When you work with different threads, you synchronize to

Currently, you are not doing any synchronization, so it does not work.

So you have two options:

  1. In a synchronized map, wrap it with the archive. Synchronize map (new hashmap . This applies synchronization to all operations, even if they come in the form of similar threads.

  2. Use the same lock while taking action on the map. I do not advise the latter method unless you are doing a lot of operations on one thread in succession, the other thread is not needed to know about it. < According to the suggestion of p> and @ zikar, the use of the third option is to use concurrent hashmap , code> archive. The synchronized map does not come at the same price, which means that it should be your preferred option.

Comments

Popular posts from this blog

Verilog Error: output or inout port "Q" must be connected to a structural net expression -

jasper reports - How to center align barcode using jasperreports and barcode4j -

c# - ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value -