Note that there are some explanatory texts on larger screens.

plurals
  1. POWhere am I not Threadsafe?
    primarykey
    data
    text
    <p>I'm using an object, which serves roughly as a wrapper for a map of Strings:</p> <pre><code>public class Wrapper { private Map&lt;String, String&gt; values; private Formatter formatter; public BigDecimal getSpecialValue() { String result = values.get("Special"); return formatter.formatNumber(result); } } </code></pre> <p>The abovementioned formatter serves roughly as a mapper for a SimpleDateFormat</p> <pre><code> public class Formatter { private static final NumberFormat NUMBER_FORMAT; public BigDecimal formatNumber(String s) { Number num = NUMBER_FORMAT.parse(s); if (num instanceof Integer) { return new BigDecimal((Integer) num); } else if (num instanceof Double) { return new BigDecimal((Double) num); } ... } } </code></pre> <p>When I access the <code>getSpecialValue()</code> method by several threads at once, some behaviour accurs, which can only be explained by the concurrent access, for example there may be a <code>NumberFormatException</code> or a <code>ParseException</code> where the parsed string is .430.430 instead of .430 and so on.</p> <p>There are two aspects which arouse my interest: 1.) The wrapper is only accessed read-only. Although access to the collection is not synchronized, I was under the impression that this should always work. 2.) In one of the first attempts to find the problem I changed the constructor of the <code>Wrapper</code> class to execute the <code>formatNumber</code> method (obviously single threaded), which eliminated all Exceptions down the execution.</p> <p>Can someone explain?</p> <p>Edit: The map in the <code>Wrapper</code> class is filled in the constructor, which most definitly happens single threaded. Afterwards the wrapper is designed such that the map is immutable.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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