Note that there are some explanatory texts on larger screens.

plurals
  1. POthreads accessing non-synchronised methods in Java
    text
    copied!<p>can I ask to explain me how threads and synchronisation works in Java?</p> <p>I want to write a high-performance application. Inside this application, I read a data from files into some nested classes, which are basically a nut-shell around HashMap.</p> <p>After the data reading is finished, I start threads which need to go through the data and perform different checks on it. However, threads never change the data!</p> <p>If I can guarantee (or at least try to guarantee;) that my threads never change the data, can I use them calling non-synchronised methods of objects containing data?</p> <p>If multiple threads access the non-synchronised method, which does not change any class field, but has some internal variables, is it safe?</p> <p>artificial example:</p> <pre><code>public class Data{ // this hash map is filled before I start threads protected Map&lt;Integer, Spike&gt; allSpikes = new HashMap&lt;Integer, Spike&gt;(); public HashMap returnBigSpikes(){ Map&lt;Integer, Spike&gt; bigSpikes = new HashMap&lt;Integer, Spike&gt;(); for (Integer i: allSpikes.keySet()){ if (allSpikes.get(i).spikeSize &gt; 100){ bigSpikes.put(i,allSpikes.get(i)); } } return bigSpikes; } } </code></pre> <p>Is it safe to call a NON-synchronised method returnBigSpikes() from threads?</p> <p>I understand now that such use-cases are potentially very dangerous, because it's hard to control, that data (e.g., returned bigSpikes) will not be modified. But I have already implemented and tested it like this and want to know if I can use results of my application now, and change the architecture later...</p> <p>What happens if I make the methods synchronised? Will be the application slowed down to 1 CPU performance? If so, how can I design it correctly and keep the performance?</p> <p>(I read about 20-40 Gb of data (log messages) into the main memory and then run threads, which need to go through the all data to find some correlation in it; each thread becomes only a part of messages to analyse; but for the analysis, the thread should compare each message from its part with many other messages from data; that's why I first decided to allow threads to read data without synchronisation).</p> <p>Thank You very much in advance.</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