Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First of all, don't initialize the map in <code>run()</code> method, there's no guarantee that the initialization only happens once. Sure in this case it doesn't matter how many times you created that map, eventually one will be set to the static reference, and others be GCed. It's just not pretty. I suggest static initialization blocks:</p> <pre><code>private final static Map&lt;String,String&gt; mapOfConstants; static { Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); // initialize map. map.put("", ""); ... // convert the map into unmodifiable mapOfConstants = Collections.unmodifiableMap(map); } </code></pre> <p>However, there's another way to share a map of constants among multiple threads. Since you are considering loading the constants from a text file, have you considered extracting the static reference from your Runnable, initialize the map elsewhere, then pass in the reference? The constructor takes an additional map reference.</p> <pre><code>public class MyRunnable implements Runnable { private final Map&lt;String,String&gt; mapOfConstants = null; private String member; public MyRunnable(String member, Map&lt;String,String&gt; mapOfConstants) { this.member = member; this.mapOfConstants = mapOfConstants; } .... } </code></pre> <p>Then in your servlet, get the map reference from say a <code>MapOfConstantsFactory</code></p> <pre><code>protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Map&lt;String, String&gt; sharedMapOfConstants = MapOfConstantsFactory.getMapOfConstants(); String myInput = request.getParameter("input"); Thread t = new Thread(new MyRunnable(myInput, sharedMapOfConstants)); t.start(); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("Process started!"); out.close(); } </code></pre> <p>This way you can write Tests against different configurations of constants, without modifying your Runnable class.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload