multithreading - Thread-safe Map in Java -


I understand the overall concept of multi-threading and synchronization but I'm new to writing thread-safe code. The following code snippet is:

  Synchronize (compiledList) {if (compiled Stylesheet Containes (xslt)) {exec = compiledStylesheets.get (xslt); } And {exec = compilation (s, import); Compiled stylesheets (xslt, f); }}   

where is compiled stylesheet a hashmap (private, last). I have some questions.

The compilation method can take a few hundred milliseconds to return. It takes a long time to lock the object, but I do not see the alternative, except that it is unnecessary for the use of the archive. In addition to the synchronized map synchronize block, right? This is the only code that hits other than the initialization / institute.

Alternatively, I know the existence of the ConcurrentHashMap , but I do not know that it is overkill in this example putIfAbsent () method used Not allowed because it does not allow me to leave the compile () method call. I do not even know that it is included in the after modification () but put () "before the problem, or if it is actually a case in this There is a matter of concern.

Edit: Spelling

For the purposes of this nature, I highly recommend

If you can not use that library, then here is a brief implementation of the use of Futureskus

  Public abstract class Through a tip cache & lt; K, V & gt; {Private Final Concurrent Map & lt; K, future & lt; V> & Gt; Cache = new concurrenthemashmap & lt; & Gt; (); Public last V mill (K key) throws interrupted, Exception exception {Future & lt; V> Ref = cache.et (key); If (ref == null) {FutureTask & lt; V> Task = New Future Tasks & lt; & Gt; (New factory (key)); Ref = cache.putIfAbsent (key, works); If (ref == null) {task.run (); Referee = work; }} Ref.get return (); } By creating the protected essence V (K) throws exceptions; Private Final Class Factory Callable & lt; V> {Key of private finals; Factory (K key) {this.key = key; } @ Override Public V call () throws an exception {make a return (key); }}}    

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 -