Java-Gaming.org    
Featured games (78)
games approved by the League of Dukes
Games in Showcase (429)
Games in Android Showcase (89)
games submitted by our members
Games in WIP (468)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  How does java handle Threads?  (Read 2864 times)
0 Members and 1 Guest are viewing this topic.
Offline Kurten

Junior Member


Medals: 2
Exp: 3 years


-w-


« Posted 2011-05-21 21:31:44 »

Im having a problem with my program again xD
Or, well, it's not necessarily a problem, but I would like to know what's going on.

My program generate random numbers at a rapid rate, about 200 per second.
I wanted to run several number generations simultaneously so I created some more threads to run almost identical operations. When running the program, one of my processor cores goes up to maybe 70% usage, while the remaining 5 cores stay below 20%. This made me suspect that all the threads might be using the same core, which is not what i want them to do since i want real time simultaneously number generation. So my question is, what is it that causes this? I have looked through the code for quite some time now but im unable to find the source of the problem. Can someone with more experience in this help me out? ^_^

//Kurten

Source:

MainClass
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
205  
206  
207  
208  
209  
210  
211  
212  
213  
214  
215  
216  
217  
218  
219  
220  
221  
222  
223  
224  
225  
226  
227  
228  
229  
230  
231  
232  
233  
234  
235  
236  
237  
238  
239  
240  
241  
242  
243  
244  
245  
246  
247  
248  
249  
250  
251  
252  
253  
254  
255  
256  
257  
258  
259  
260  
261  
262  
263  
264  
265  
266  
267  
268  
269  
270  
271  
272  
273  
274  
275  
276  
277  
278  
279  
280  
281  
282  
283  
284  
285  
286  
287  
288  
289  
290  
291  
292  
293  
294  
295  
296  
297  
298  
299  
300  
301  
302  
303  
304  
305  
306  
307  
308  
309  
310  
311  
312  
313  
314  
315  
316  
317  
318  
319  
320  
321  
322  
323  
324  
325  
326  
327  
328  
329  
330  
331  
332  
333  
334  
335  
336  
337  
338  
339  
340  
341  
342  
343  
344  
345  
346  
347  
348  
349  
350  
351  
352  
353  
354  
355  
356  
357  
358  
359  
360  
361  
362  
363  
364  
365  
366  
367  
368  
369  
370  
371  
372  
373  
374  
375  
376  
377  
378  
379  
380  
381  
382  
383  
384  
385  
386  
387  
388  
389  
390  
391  
392  
393  
394  
395  
396  
397  
398  
399  
400  
401  
402  
403  
404  
405  
406  
407  
408  
409  
410  
411  
412  
413  
414  
415  
416  
417  
418  
419  
420  
421  
422  
423  
424  
425  
426  
427  
428  
429  
430  
431  
432  
433  
434  
435  
436  
437  
438  
439  
440  
441  
442  
443  
444  
445  
446  
447  
448  
449  
450  
451  
452  
453  
454  
455  
456  
457  
458  
459  
460  
461  
462  
463  
464  
465  
466  
467  
468  
469  
470  
471  
472  
473  
474  
475  
476  
477  
478  
479  
480  
481  
482  
483  
484  
485  
486  
487  
488  
489  
490  
491  
492  
493  
494  
495  
496  
497  
498  
499  
500  
501  
502  
503  
504  
505  
506  
507  
508  
509  
510  
511  
512  
513  
514  
515  
516  
517  
518  
519  
520  
521  
522  
523  
524  
525  
526  
527  
528  
529  
530  
531  
532  
533  
534  
535  
536  
537  
538  
539  
540  
541  
542  
543  
544  
545  
546  
547  
548  
549  
550  
551  
552  
553  
554  
555  
556  
557  
558  
559  
560  
561  
562  
563  
564  
565  
566  
567  
568  
569  
570  
571  
572  
573  
574  
575  
576  
577  
578  
579  
580  
581  
582  
583  
584  
585  
586  
587  
588  
589  
590  
591  
592  
593  
594  
595  
596  
597  
598  
599  
600  
601  
602  
603  
604  
605  
606  
607  
608  
609  
610  
611  
612  
613  
614  
615  
616  
617  
618  
619  
620  
621  
622  
623  
624  
625  
626  
627  
628  
629  
630  
631  
632  
633  
634  
635  
636  
637  
638  
639  
640  
641  
642  
643  
644  
645  
646  
647  
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * @version 1.4
 * <p>
 * Last updated 2011-05-21
 */


@SuppressWarnings("serial")
public class MainEngine extends JPanel implements Runnable{

   /*************
    * Variables!
    *************/

   //xMins is how many minutes you want the simulation to run for!
  int xMins = 10;
   
   Random rand = new Random();
   
   int letterPosX0 = 7;
   int letterPosY0;
   
   int resultNumber0;
   
   long numbersTotal0 = 0;
   
   //Time variables
  double time1;
   double time2;
   double timeTaken;
   double simulationTime = xMins*(60*1000);
   
   //Booleans for numbers
  boolean is0_0 = false;
   boolean is1_0 = false;
   boolean is2_0 = false;
   boolean is3_0 = false;
   boolean is4_0 = false;
   boolean is5_0 = false;
   boolean is6_0 = false;
   boolean is7_0 = false;
   boolean is8_0 = false;
   boolean is9_0 = false;
   
   //For keeping track of the streaks
  int streak2_0;
   int streak3_0;
   int streak4_0;
   int streak5_0;
   int streak6_0;
   
   int timesCalled0 = 1;
   boolean timesCalledReset0 = false;
   
   boolean redraw0 = false;
   boolean running0 = true;
   boolean drawLetters0 = true;
   
   Graphics2D g2d;
   BufferedImage backbuffer;
   JPanel p1 = new JPanel();
   JFrame f = new JFrame();
   
   //Class objects
  Calculation1 c1;
   Calculation2 c2;
   Calculation3 c3;
   
   //Threads
  Thread calcLoop0;
   Thread calcLoop1;
   Thread calcLoop2;
   Thread calcLoop3;
   
   FileWriter outFile0;
   PrintWriter out0;
   
   
   /*******************************
    * Code for closing the program
    *******************************/

   WindowListener windowListener = new WindowAdapter(){
     
      // anonymous WindowAdapter class
     public void windowClosing (WindowEvent w){
         exitProgram();
      } // end windowClosing
  };// end anonymous class

   public void exitProgram(){
      // Whatever application code you want to do on close, e.g.
     c1.running1 = false;
      c2.running2 = false;
      c3.running3 = false;
      running0 = false;
   
      // Whatever code you want to actually close the JFrame, e.g.
     f.setVisible(false);
      f.dispose();
   }
   
   
   /**************************
    * Main Method starts here
    * @param args
    **************************/

   public static void main(String[] args){
      MainEngine me = new MainEngine();
      me.initCalculate();
   }
   
   public void initCalculate(){
      initgfx();
     
      calcLoop0 = new Thread(this);
      calcLoop1 = new Thread(c1);
      calcLoop2 = new Thread(c2);
      calcLoop3 = new Thread(c3);
     
      calcLoop0.start();  
      calcLoop1.start();
      calcLoop2.start();
      calcLoop3.start();
   }

   @Override
   public void run() {
      while(running0){
         
         time1 = System.nanoTime();
         initWriters();
         updateGraphics();
         checkVariables();
         writeToFiles();
         repaint();
         time2 = System.nanoTime() - time1;
         
         try{
            Thread.sleep(5);
         }catch(InterruptedException e){
            e.printStackTrace();
            System.out.println("Interrupted Exception in MainEngine's calcLoop0");
         }
         
         timeTaken += (time2/1000000) + 5;
         if(timeTaken >= simulationTime){
            exitProgram();
         }
      }
   }
   
   /******************************
    * Initialize the file writers
    ******************************/

   public void initWriters(){
      try{
           outFile0 = new FileWriter("C:\\chaos studies\\Mathematical code\\numbers0.txt");
           out0 = new PrintWriter(outFile0);
      }catch(IOException iex){
         iex.printStackTrace();
         System.out.println("IO exception in MainEngine");
      }
   }
   
   @Override
   public void update(Graphics g){
      System.out.println("updating");
      paint(g);
   }
   
   /********************************************************
    * Checks if the number computed is a streak is a streak
    ********************************************************/

   public void checkVariables(){
      switch(resultNumber0){
      case 0:
         if(is0_0 == false){
            timesCalledReset0 = true;
         }
         if(timesCalledReset0 == true){
            timesCalled0 = 1;
         }
         timesCalledReset0 = false;
         if(is0_0 = true){
            streak2_0++;
            if(timesCalled0 == 2){
               streak2_0--;
               streak3_0++;
            }
            if(timesCalled0 == 3){
               streak2_0--;
               streak3_0--;
               streak4_0++;
            }
            if(timesCalled0 == 4){
               streak2_0--;
               streak4_0--;
               streak5_0++;
            }
            timesCalled0++;
         }
         is0_0 = true;
         is1_0 = false;
         is2_0 = false;
         is3_0 = false;
         is4_0 = false;
         is5_0 = false;
         is6_0 = false;
         is7_0 = false;
         is8_0 = false;
         is9_0 = false;
         break;
     
      case 1:
         if(is1_0 == false){
            timesCalledReset0 = true;
         }
         if(timesCalledReset0 == true){
            timesCalled0 = 1;
         }
         timesCalledReset0 = false;
         if(is1_0 == true){
            streak2_0++;
            if(timesCalled0 == 2){
               streak2_0--;
               streak3_0++;
            }
            if(timesCalled0 == 3){
               streak2_0--;
               streak3_0--;
               streak4_0++;
            }
            if(timesCalled0 == 4){
               streak2_0--;
               streak4_0--;
               streak5_0++;
            }
            timesCalled0++;
         }
         is1_0 = true;
         is0_0 = false;
         is2_0 = false;
         is3_0 = false;
         is4_0 = false;
         is5_0 = false;
         is6_0 = false;
         is7_0 = false;
         is8_0 = false;
         is9_0 = false;
         break;
         
      case 2:
         if(is2_0 == false){
            timesCalledReset0 = true;
         }
         if(timesCalledReset0 == true){
            timesCalled0 = 1;
         }
         timesCalledReset0 = false;
         if(is2_0 == true){
            streak2_0++;
            if(timesCalled0 == 2){
               streak2_0--;
               streak3_0++;
            }
            if(timesCalled0 == 3){
               streak2_0--;
               streak3_0--;
               streak4_0++;
            }
            if(timesCalled0 == 4){
               streak2_0--;
               streak4_0--;
               streak5_0++;
            }
            timesCalled0++;
         }
         is2_0 = true;
         is0_0 = false;
         is1_0 = false;
         is3_0 = false;
         is4_0 = false;
         is5_0 = false;
         is6_0 = false;
         is7_0 = false;
         is8_0 = false;
         is9_0 = false;
         break;
     
      case 3:
         if(is3_0 == false){
            timesCalledReset0 = true;
         }
         if(timesCalledReset0 == true){
            timesCalled0 = 1;
         }
         timesCalledReset0 = false;
         if(is3_0 == true){
            streak2_0++;
            if(timesCalled0 == 2){
               streak2_0--;
               streak3_0++;
            }
            if(timesCalled0 == 3){
               streak2_0--;
               streak3_0--;
               streak4_0++;
            }
            if(timesCalled0 == 4){
               streak2_0--;
               streak4_0--;
               streak5_0++;
            }
            timesCalled0++;
         }
         is3_0 = true;
         is0_0 = false;
         is1_0 = false;
         is2_0 = false;
         is4_0 = false;
         is5_0 = false;
         is6_0 = false;
         is7_0 = false;
         is8_0 = false;
         is9_0 = false;
         break;
     
      case 4:
         if(is4_0 == false){
            timesCalledReset0 = true;
         }
         if(timesCalledReset0 == true){
            timesCalled0 = 1;
         }
         timesCalledReset0 = false;
         if(is4_0 == true){
            streak2_0++;
            if(timesCalled0 == 2){
               streak2_0--;
               streak3_0++;
            }
            if(timesCalled0 == 3){
               streak2_0--;
               streak3_0--;
               streak4_0++;
            }
            if(timesCalled0 == 4){
               streak2_0--;
               streak4_0--;
               streak5_0++;
            }
            timesCalled0++;
         }
         is4_0 = true;
         is0_0 = false;
         is1_0 = false;
         is2_0 = false;
         is3_0 = false;
         is5_0 = false;
         is6_0 = false;
         is7_0 = false;
         is8_0 = false;
         is9_0 = false;
         break;
     
      case 5:
         if(is5_0 == false){
            timesCalledReset0 = true;
         }
         if(timesCalledReset0 == true){
            timesCalled0 = 1;
         }
         timesCalledReset0 = false;
         if(is5_0 == true){
            streak2_0++;
            if(timesCalled0 == 2){
               streak2_0--;
               streak3_0++;
            }
            if(timesCalled0 == 3){
               streak2_0--;
               streak3_0--;
               streak4_0++;
            }
            if(timesCalled0 == 4){
               streak2_0--;
               streak4_0--;
               streak5_0++;
            }
            timesCalled0++;
         }
         is5_0 = true;
         is0_0 = false;
         is1_0 = false;
         is2_0 = false;
         is3_0 = false;
         is4_0 = false;
         is6_0 = false;
         is7_0 = false;
         is8_0 = false;
         is9_0 = false;
         break;
     
      case 6:
         if(is6_0 == false){
            timesCalledReset0 = true;
         }
         if(timesCalledReset0 == true){
            timesCalled0 = 1;
         }
         timesCalledReset0 = false;
         if(is6_0 == true){
            streak2_0++;
            if(timesCalled0 == 2){
               streak2_0--;
               streak3_0++;
            }
            if(timesCalled0 == 3){
               streak2_0--;
               streak3_0--;
               streak4_0++;
            }
            if(timesCalled0 == 4){
               streak2_0--;
               streak4_0--;
               streak5_0++;
            }
            timesCalled0++;
         }
         is6_0 = true;
         is0_0 = false;
         is1_0 = false;
         is2_0 = false;
         is3_0 = false;
         is4_0 = false;
         is5_0 = false;
         is7_0 = false;
         is8_0 = false;
         is9_0 = false;
         break;
         
      case 7:
         if(is7_0 == false){
            timesCalledReset0 = true;
         }
         if(timesCalledReset0 == true){
            timesCalled0 = 1;
         }
         timesCalledReset0 = false;
         if(is7_0 == true){
            streak2_0++;
            if(timesCalled0 == 2){
               streak2_0--;
               streak3_0++;
            }
            if(timesCalled0 == 3){
               streak2_0--;
               streak3_0--;
               streak4_0++;
            }
            if(timesCalled0 == 4){
               streak2_0--;
               streak4_0--;
               streak5_0++;
            }
            timesCalled0++;
         }
         is7_0 = true;
         is0_0 = false;
         is1_0 = false;
         is2_0 = false;
         is3_0 = false;
         is4_0 = false;
         is5_0 = false;
         is6_0 = false;
         is8_0 = false;
         is9_0 = false;
         break;
     
      case 8:
         if(is8_0 == false){
            timesCalledReset0 = true;
         }
         if(timesCalledReset0 == true){
            timesCalled0 = 1;
         }
         timesCalledReset0 = false;
         if(is8_0 == true){
            streak2_0++;
            if(timesCalled0 == 2){
               streak2_0--;
               streak3_0++;
            }
            if(timesCalled0 == 3){
               streak2_0--;
               streak3_0--;
               streak4_0++;
            }
            if(timesCalled0 == 4){
               streak2_0--;
               streak4_0--;
               streak5_0++;
            }
            timesCalled0++;
         }
         is8_0 = true;
         is0_0 = false;
         is1_0 = false;
         is2_0 = false;
         is3_0 = false;
         is4_0 = false;
         is5_0 = false;
         is6_0 = false;
         is7_0 = false;
         is9_0 = false;
         break;
     
      case 9:
         if(is9_0 == false){
            timesCalledReset0 = true;
         }
         if(timesCalledReset0 == true){
            timesCalled0 = 1;
         }
         timesCalledReset0 = false;
         if(is9_0 == true){
            streak2_0++;
            if(timesCalled0 == 2){
               streak2_0--;
               streak3_0++;
            }
            if(timesCalled0 == 3){
               streak2_0--;
               streak3_0--;
               streak4_0++;
            }
            if(timesCalled0 == 4){
               streak2_0--;
               streak4_0--;
               streak5_0++;
            }
            timesCalled0++;
         }
         is9_0 = true;
         is0_0 = false;
         is1_0 = false;
         is2_0 = false;
         is3_0 = false;
         is4_0 = false;
         is5_0 = false;
         is6_0 = false;
         is7_0 = false;
         is8_0 = false;
         break;
      }
   }
   

   
   public void initgfx(){
      backbuffer = new BufferedImage(1680, 1050, BufferedImage.TYPE_INT_RGB);
      g2d = backbuffer.createGraphics();
      f.setSize(1680, 1050);
      //f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     f.getContentPane().add(this);
      f.setVisible(true);
      g2d.setColor(Color.BLACK);
      g2d.fillRect(0, 0, 1680, 1050);
      c1 = new Calculation1(this, g2d);
      c2 = new Calculation2(this, g2d);
      c3 = new Calculation3(this, g2d);
      f.setDefaultCloseOperation (JFrame.DO_NOTHING_ON_CLOSE);
      f.addWindowListener( windowListener );
   }

   public void updateGraphics(){
     
      if(drawLetters0 == true){
         g2d.setColor(Color.WHITE);
         resultNumber0 = rand.nextInt(10);
         g2d.drawString("" + resultNumber0, letterPosX0, letterPosY0);
         letterPosX0 += 7;  
      }
     
      numbersTotal0++;
      System.out.println("Total digits " + numbersTotal0);
     
      if(letterPosX0 >= 322){
         letterPosX0 = 7;
         letterPosY0 += 11;
      }
     
     
      if(letterPosY0 >= 1039){
         g2d.copyArea(0, 0, 322, 1050, 0, -11);
         
         redraw0 = true;
         g2d.setColor(Color.WHITE);
         letterPosY0 = 1033;
      }
     
      if(redraw0 = false){
         g2d.setColor(Color.BLACK);
         g2d.drawRect(0, 0, 1680, 1050);
      }
     
      System.out.println("Number0 = " + resultNumber0);
      System.out.println("Times called0 " + timesCalled0);
      System.out.println("streak2_0 " + streak2_0);
      System.out.println("streak3_0 " + streak3_0);
      System.out.println("Streak4_0 " + streak4_0);
      System.out.println("Streak5_ " + streak5_0);
   }
   
   /**
    * Writes statistics to text files located in the main C: directory
    */

   public void writeToFiles(){
      out0.println(resultNumber0);
      out0.println("A total amount of " + numbersTotal0 + " digits computed");
      out0.println("Ran for " + (timeTaken/1000) + " Seconds");
      out0.println("Times called current digit: " + timesCalled0);
      out0.println("2 Digits in a row: " + streak2_0);
      out0.println("3 Digits in a row: " + streak3_0);
      out0.println("4 Digits in a row: " + streak4_0);
      out0.println("5 Digits in a row: " + streak5_0);
      out0.close();
   }
   
   public void paint(Graphics g){
      g.drawImage(backbuffer, 0, 0, null);
   }
   
}


1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
205  
206  
207  
208  
209  
210  
211  
212  
213  
214  
215  
216  
217  
218  
219  
220  
221  
222  
223  
224  
225  
226  
227  
228  
229  
230  
231  
232  
233  
234  
235  
236  
237  
238  
239  
240  
241  
242  
243  
244  
245  
246  
247  
248  
249  
250  
251  
252  
253  
254  
255  
256  
257  
258  
259  
260  
261  
262  
263  
264  
265  
266  
267  
268  
269  
270  
271  
272  
273  
274  
275  
276  
277  
278  
279  
280  
281  
282  
283  
284  
285  
286  
287  
288  
289  
290  
291  
292  
293  
294  
295  
296  
297  
298  
299  
300  
301  
302  
303  
304  
305  
306  
307  
308  
309  
310  
311  
312  
313  
314  
315  
316  
317  
318  
319  
320  
321  
322  
323  
324  
325  
326  
327  
328  
329  
330  
331  
332  
333  
334  
335  
336  
337  
338  
339  
340  
341  
342  
343  
344  
345  
346  
347  
348  
349  
350  
351  
352  
353  
354  
355  
356  
357  
358  
359  
360  
361  
362  
363  
364  
365  
366  
367  
368  
369  
370  
371  
372  
373  
374  
375  
376  
377  
378  
379  
380  
381  
382  
383  
384  
385  
386  
387  
388  
389  
390  
391  
392  
393  
394  
395  
396  
397  
398  
399  
400  
401  
402  
403  
404  
405  
406  
407  
408  
409  
410  
411  
412  
413  
414  
415  
416  
417  
418  
419  
420  
421  
422  
423  
424  
425  
426  
427  
428  
429  
430  
431  
432  
433  
434  
435  
436  
437  
438  
439  
440  
441  
442  
443  
444  
445  
446  
447  
448  
449  
450  
451  
452  
453  
454  
455  
456  
457  
458  
459  
460  
461  
462  
463  
464  
465  
466  
467  
468  
469  
470  
471  
472  
473  
474  
475  
476  
477  
478  
479  
480  
481  
482  
483  
484  
485  
486  
487  
488  
489  
490  
491  
492  
493  
494  
495  
496  
497  
498  
499  
500  
501  
502  
503  
504  
505  
506  
507  
508  
509  
510  
511  
512  
513  
514  
515  
516  
517  
518  
519  
520  
521  
522  
import java.awt.Graphics2D;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

/**
 * @author Kurten
 *
 */


public class Calculation1 implements Runnable{

   Random rand = new Random();
   
   //For measuring time
  double time1;
   double time2;
   double timeTaken;
   
   int letterPosX1 = 329;
   int letterPosY1;
   int number1;
   int resultNumber1;
   long numbersTotal1 = 0;
   
   //Booleans for numbers
  boolean is0_1 = false;
   boolean is1_1 = false;
   boolean is2_1 = false;
   boolean is3_1 = false;
   boolean is4_1 = false;
   boolean is5_1 = false;
   boolean is6_1 = false;
   boolean is7_1 = false;
   boolean is8_1 = false;
   boolean is9_1 = false;
   
   //For keeping track of the streaks
  int streak2_1;
   int streak3_1;
   int streak4_1;
   int streak5_1;
   int streak6_1;
   
   int timesCalled1 = 1;
   boolean timesCalledReset1 = false;
   
   boolean redraw1 = false;
   boolean running1 = false;
   boolean drawLetters1 = true;
   
   FileWriter outFile1;
   PrintWriter out1;
   
   Graphics2D g2d;
   MainEngine me;
   
   //Constructor
  public Calculation1(MainEngine m, Graphics2D g){
      me = m;
      g2d = g;
   }
   
   @Override
   public void run() {
     
      running1 = true;
     
      while(running1){
         try{
            time1 = System.nanoTime();
            initWriters();
            updateGraphics();
            checkVariables();
            writeToFiles();
            time2 = System.nanoTime() - time1;
            Thread.sleep(5);
            timeTaken += (time2/1000000) + 5;
         }catch(InterruptedException e){}
      }
   }
   
   /**
    * Initialize the file writers
    */

   public void initWriters(){
      try{
           outFile1 = new FileWriter("C:\\chaos studies\\Mathematical code\\numbers1.txt");
           out1 = new PrintWriter(outFile1);
      }catch(IOException iex){}
   }
   
   
   /**
    * Checks if the number is a streak
    */

   public void checkVariables(){
      switch(resultNumber1){
      case 0:
         if(is0_1 == false){
            timesCalledReset1 = true;
         }
         if(timesCalledReset1 == true){
            timesCalled1 = 1;
         }
         timesCalledReset1 = false;
         if(is0_1 = true){
            streak2_1++;
            if(timesCalled1 == 2){
               streak2_1--;
               streak3_1++;
            }
            if(timesCalled1 == 3){
               streak2_1--;
               streak3_1--;
               streak4_1++;
            }
            if(timesCalled1 == 4){
               streak2_1--;
               streak4_1--;
               streak5_1++;
            }
            timesCalled1++;
         }
         is0_1 = true;
         is1_1 = false;
         is2_1 = false;
         is3_1 = false;
         is4_1 = false;
         is5_1 = false;
         is6_1 = false;
         is7_1 = false;
         is8_1 = false;
         is9_1 = false;
         break;
     
      case 1:
         if(is1_1 == false){
            timesCalledReset1 = true;
         }
         if(timesCalledReset1 == true){
            timesCalled1 = 1;
         }
         timesCalledReset1 = false;
         if(is1_1 == true){
            streak2_1++;
            if(timesCalled1 == 2){
               streak2_1--;
               streak3_1++;
            }
            if(timesCalled1 == 3){
               streak2_1--;
               streak3_1--;
               streak4_1++;
            }
            if(timesCalled1 == 4){
               streak2_1--;
               streak4_1--;
               streak5_1++;
            }
            timesCalled1++;
         }
         is1_1 = true;
         is0_1 = false;
         is2_1 = false;
         is3_1 = false;
         is4_1 = false;
         is5_1 = false;
         is6_1 = false;
         is7_1 = false;
         is8_1 = false;
         is9_1 = false;
         break;
         
      case 2:
         if(is2_1 == false){
            timesCalledReset1 = true;
         }
         if(timesCalledReset1 == true){
            timesCalled1 = 1;
         }
         timesCalledReset1 = false;
         if(is2_1 == true){
            streak2_1++;
            if(timesCalled1 == 2){
               streak2_1--;
               streak3_1++;
            }
            if(timesCalled1 == 3){
               streak2_1--;
               streak3_1--;
               streak4_1++;
            }
            if(timesCalled1 == 4){
               streak2_1--;
               streak4_1--;
               streak5_1++;
            }
            timesCalled1++;
         }
         is2_1 = true;
         is0_1 = false;
         is1_1 = false;
         is3_1 = false;
         is4_1 = false;
         is5_1 = false;
         is6_1 = false;
         is7_1 = false;
         is8_1 = false;
         is9_1 = false;
         break;
     
      case 3:
         if(is3_1 == false){
            timesCalledReset1 = true;
         }
         if(timesCalledReset1 == true){
            timesCalled1 = 1;
         }
         timesCalledReset1 = false;
         if(is3_1 == true){
            streak2_1++;
            if(timesCalled1 == 2){
               streak2_1--;
               streak3_1++;
            }
            if(timesCalled1 == 3){
               streak2_1--;
               streak3_1--;
               streak4_1++;
            }
            if(timesCalled1 == 4){
               streak2_1--;
               streak4_1--;
               streak5_1++;
            }
            timesCalled1++;
         }
         is3_1 = true;
         is0_1 = false;
         is1_1 = false;
         is2_1 = false;
         is4_1 = false;
         is5_1 = false;
         is6_1 = false;
         is7_1 = false;
         is8_1 = false;
         is9_1 = false;
         break;
     
      case 4:
         if(is4_1 == false){
            timesCalledReset1 = true;
         }
         if(timesCalledReset1 == true){
            timesCalled1 = 1;
         }
         timesCalledReset1 = false;
         if(is4_1 == true){
            streak2_1++;
            if(timesCalled1 == 2){
               streak2_1--;
               streak3_1++;
            }
            if(timesCalled1 == 3){
               streak2_1--;
               streak3_1--;
               streak4_1++;
            }
            if(timesCalled1 == 4){
               streak2_1--;
               streak4_1--;
               streak5_1++;
            }
            timesCalled1++;
         }
         is4_1 = true;
         is0_1 = false;
         is1_1 = false;
         is2_1 = false;
         is3_1 = false;
         is5_1 = false;
         is6_1 = false;
         is7_1 = false;
         is8_1 = false;
         is9_1 = false;
         break;
     
      case 5:
         if(is5_1 == false){
            timesCalledReset1 = true;
         }
         if(timesCalledReset1 == true){
            timesCalled1 = 1;
         }
         timesCalledReset1 = false;
         if(is5_1 == true){
            streak2_1++;
            if(timesCalled1 == 2){
               streak2_1--;
               streak3_1++;
            }
            if(timesCalled1 == 3){
               streak2_1--;
               streak3_1--;
               streak4_1++;
            }
            if(timesCalled1 == 4){
               streak2_1--;
               streak4_1--;
               streak5_1++;
            }
            timesCalled1++;
         }
         is5_1 = true;
         is0_1 = false;
         is1_1 = false;
         is2_1 = false;
         is3_1 = false;
         is4_1 = false;
         is6_1 = false;
         is7_1 = false;
         is8_1 = false;
         is9_1 = false;
         break;
     
      case 6:
         if(is6_1 == false){
            timesCalledReset1 = true;
         }
         if(timesCalledReset1 == true){
            timesCalled1 = 1;
         }
         timesCalledReset1 = false;
         if(is6_1 == true){
            streak2_1++;
            if(timesCalled1 == 2){
               streak2_1--;
               streak3_1++;
            }
            if(timesCalled1 == 3){
               streak2_1--;
               streak3_1--;
               streak4_1++;
            }
            if(timesCalled1 == 4){
               streak2_1--;
               streak4_1--;
               streak5_1++;
            }
            timesCalled1++;
         }
         is6_1 = true;
         is0_1 = false;
         is1_1 = false;
         is2_1 = false;
         is3_1 = false;
         is4_1 = false;
         is5_1 = false;
         is7_1 = false;
         is8_1 = false;
         is9_1 = false;
         break;
         
      case 7:
         if(is7_1 == false){
            timesCalledReset1 = true;
         }
         if(timesCalledReset1 == true){
            timesCalled1 = 1;
         }
         timesCalledReset1 = false;
         if(is7_1 == true){
            streak2_1++;
            if(timesCalled1 == 2){
               streak2_1--;
               streak3_1++;
            }
            if(timesCalled1 == 3){
               streak2_1--;
               streak3_1--;
               streak4_1++;
            }
            if(timesCalled1 == 4){
               streak2_1--;
               streak4_1--;
               streak5_1++;
            }
            timesCalled1++;
         }
         is7_1 = true;
         is0_1 = false;
         is1_1 = false;
         is2_1 = false;
         is3_1 = false;
         is4_1 = false;
         is5_1 = false;
         is6_1 = false;
         is8_1 = false;
         is9_1 = false;
         break;
     
      case 8:
         if(is8_1 == false){
            timesCalledReset1 = true;
         }
         if(timesCalledReset1 == true){
            timesCalled1 = 1;
         }
         timesCalledReset1 = false;
         if(is8_1 == true){
            streak2_1++;
            if(timesCalled1 == 2){
               streak2_1--;
               streak3_1++;
            }
            if(timesCalled1 == 3){
               streak2_1--;
               streak3_1--;
               streak4_1++;
            }
            if(timesCalled1 == 4){
               streak2_1--;
               streak4_1--;
               streak5_1++;
            }
            timesCalled1++;
         }
         is8_1 = true;
         is0_1 = false;
         is1_1 = false;
         is2_1 = false;
         is3_1 = false;
         is4_1 = false;
         is5_1 = false;
         is6_1 = false;
         is7_1 = false;
         is9_1 = false;
         break;
     
      case 9:
         if(is9_1 == false){
            timesCalledReset1 = true;
         }
         if(timesCalledReset1 == true){
            timesCalled1 = 1;
         }
         timesCalledReset1 = false;
         if(is9_1 == true){
            streak2_1++;
            if(timesCalled1 == 2){
               streak2_1--;
               streak3_1++;
            }
            if(timesCalled1 == 3){
               streak2_1--;
               streak3_1--;
               streak4_1++;
            }
            if(timesCalled1 == 4){
               streak2_1--;
               streak4_1--;
               streak5_1++;
            }
            timesCalled1++;
         }
         is9_1 = true;
         is0_1 = false;
         is1_1 = false;
         is2_1 = false;
         is3_1 = false;
         is4_1 = false;
         is5_1 = false;
         is6_1 = false;
         is7_1 = false;
         is8_1 = false;
         break;
      }
   }
   
   
   public void updateGraphics(){
      resultNumber1 = rand.nextInt(10);
     
      numbersTotal1++;
     
      g2d.drawString("" + resultNumber1, letterPosX1, letterPosY1);
     
      if(letterPosX1 >= 644){
         letterPosX1 = 329;
         letterPosY1 += 11;
      }
      letterPosX1 += 7;
      if(letterPosY1 >= 1039){
         g2d.copyArea(329, 0, 322, 1050, 0, -11);
         letterPosY1 = 1033;
      }
     
      System.out.println("Number1 = " + resultNumber1);
      System.out.println("Times called1 " + timesCalled1);
      System.out.println("streak2_1 " + streak2_1);
      System.out.println("streak3_1 " + streak3_1);
      System.out.println("Streak4_1 " + streak4_1);
      System.out.println("Streak5_1 " + streak5_1);
   }
   
   /**
    * Writes statistics to text files located in the main C: directory
    */

   public void writeToFiles(){
      out1.println(resultNumber1);
      out1.println("A total amount of " + numbersTotal1 + " digits computed");
      out1.println("Ran for " + (timeTaken/1000) + " Seconds");
      out1.println("Times called current digit: " + timesCalled1);
      out1.println("2 Digits in a row: " + streak2_1);
      out1.println("3 Digits in a row: " + streak3_1);
      out1.println("4 Digits in a row: " + streak4_1);
      out1.println("5 Digits in a row: " + streak5_1);
      out1.close();
   }
}


I apologize if the code is a bit clunky.
Also, there are 2 more classes which are identical to Calculation1, they are called Calculation2, and 3.
Online Roquen
« Reply #1 - Posted 2011-05-21 21:49:07 »

I'm going to completely ignore your question and ask: What do you really want to do here?
Offline Riven
« League of Dukes »

JGO Overlord


Medals: 613
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #2 - Posted 2011-05-21 21:49:31 »

Without actualy having understood the code...

Line 197:
1  
if(is0_0 = true){


Highly suspicious.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Kurten

Junior Member


Medals: 2
Exp: 3 years


-w-


« Reply #3 - Posted 2011-05-21 21:51:50 »

@Roquen: It's a program that generates lots of numbers and stores them in text files, its for probability studies =) I want each thread to run on one core each, or split them apart so they don't use the same core.

@Riven: Oh, thanks for finding that bug, must have forgotten to put a second = sign there, now that's embarrassing xD

Also, i apologize if the code is long and hard to understand. The entire checkVariables method is a big cluster f**k of if statements and im terribly sorry for that solution, but i couldn't think of any other way to implement the functionality i wanted.
Offline pjt33
« Reply #4 - Posted 2011-05-21 22:01:09 »

@Riven: Oh, thanks for finding that bug, must have forgotten to put a second = sign there, now that's embarrassing xD
No, you put in an additional "= true". There's no need to compare a boolean to another boolean in order to convert it into a boolean. The only case I can see where it's useful is "if (x == y)", which is slightly more transparent than "if (!(x ^y))".

To answer the original question: I observe that if I have several Java threads doing expensive calculations then all four of my cores show heavy use. I therefore conclude that Java does use native threads correctly, and that what you're observing is that your calculations aren't expensive enough for the OS to bother moving the threads across CPUs. I believe that in general it's good that the OS only uses as many CPUs as are necessary to do the work because that allows the others to be suspended and saves energy.
Offline Kurten

Junior Member


Medals: 2
Exp: 3 years


-w-


« Reply #5 - Posted 2011-05-21 22:07:01 »

Thanks for the reply, a friend of mine had a theory that it could be a power saving setting but yours sound more plausible. The thing is, I have some processing power to spare since I run a hexa-core processor. Is it any way to force it to use different cores?
Online Roquen
« Reply #6 - Posted 2011-05-21 22:09:38 »

java.util.Random is a 64-bit linear congruent generator.  Everything is known about their properties.  So, what's your real question?.  You want to consume more of your CPUs?  Change the sleeps to zero.
Offline Kurten

Junior Member


Medals: 2
Exp: 3 years


-w-


« Reply #7 - Posted 2011-05-21 22:21:15 »

Yes, my real question is how do i make it consume more of my processor's resources without modifying the sleep if that is possible?
I know that sounds really stupid, but i really want to force it to use all my cores.

Would you suggest using Math.random instead of util.Random?
Im not really that experienced in dealing with random numbers and threads.

EDIT: Seems like your theory was indeed correct pjt33, i changed the sleep time to 1 ms and all my 6 cores went active. The source of the problem was not java, thanks for showing me that ^_^

Also, sorry for confusing you guys.
Offline Riven
« League of Dukes »

JGO Overlord


Medals: 613
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #8 - Posted 2011-05-21 22:36:19 »

You can spawn hundreds of threads, if you really want each thread to sleep and and more samples per second.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Offline biro

Junior Member


Medals: 1
Projects: 1



« Reply #9 - Posted 2011-05-22 01:16:08 »

Hello,
that's a good bridge to another question:
Does anyone know, how to talk to a specific CPU core?
Par example:
I have 2 Threads, and I want that the first Thread goes to core 1 and the other to core 2 (and I already know that java does that automaticaly), does anyone know how to do that, how to talk to an specific core?

Greetings
biro
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Riven
« League of Dukes »

JGO Overlord


Medals: 613
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #10 - Posted 2011-05-22 01:27:35 »

Java doesn't do that, the OS does that for you.

You can set the core affinity of the entire process through the taskmanager.

To set the core-affinity per thread, you need native code. You can't do that with Java.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Offline ra4king

JGO Kernel


Medals: 322
Projects: 2
Exp: 4 years


I'm the King!


« Reply #11 - Posted 2011-05-22 01:41:49 »

Would you suggest using Math.random instead of util.Random?
Im not really that experienced in dealing with random numbers and threads.
Math.random uses java.util.Random ;P

Offline philfrei
« Reply #12 - Posted 2011-05-22 05:51:09 »

If all the threads call Math.random, aren't they all making use of the same code loaded in RAM? Math.random is a static method, right? So, is everything running through that single piece of code, in whichever core has loaded it?

Or am I conceptually way off here?

I noticed there is this, but it is SE7 and I have no experience with it (for concurrent calls to random number generator):
http://download.oracle.com/javase/tutorial/essential/concurrency/threadlocalrandom.html

"Greetings my friends! We are all interested in the future, for that is where you and I are going to spend the rest of our lives!" -- The Amazing Criswell
Offline ra4king

JGO Kernel


Medals: 322
Projects: 2
Exp: 4 years


I'm the King!


« Reply #13 - Posted 2011-05-22 06:57:49 »

Math holds 1 instance of Random. Here is the code inside Math.random:
1  
2  
3  
4  
5  
6  
7  
8  
9  
public static double random() {
    if(randomNumberGenerator == null) initRNG();
    return randomNumberGenerator.nextDouble();
}

private static synchronized void initRNG() {
    if(randomNumberGenerator == null)
        randomNumberGenerator = new Random();
}

Online Roquen
« Reply #14 - Posted 2011-05-22 10:11:10 »

@phifrei:  Yes, as raking shows explicitly, it's a static method (which is reentrant) that calls an (unoverrided, thread-safe) method.

WRT: Thread local randoms. Without looking at the code, I really don't see any point.
Offline philfrei
« Reply #15 - Posted 2011-05-22 21:13:51 »

Quote
WRT: Thread local randoms. Without looking at the code, I really don't see any point.
Well, my curiousity has been piqued about a couple aspects, not knowing much about how the JVM works with multiprocessing/parallel processing CPUs. I could see that "which core" might not make any practical difference at this point, though, that we are well below the point where it might impact actual performance.

1) Will all calls to Math.random() (or to any static method) all invoke the same code, which presumably resides in one or another core of a processor that allows parallel processing?
2) Will the calls "bring along" any other code to that same cpu?
3) Will all calls to all static Math methods go to the same cpu/core?
4) If the future of performance gain comes from the ability to multiprocess, wouldn't code that allows the system to distribute it across multiple processes run better than code that must be executed via a single "place" in the system?
5) When distributing processes, does the implementation tend to load one or another subsystem up to a threshold and THEN start offloading processes to other subsystems, or does it try to evenly divide things up from the get-go?
6) Is there a simple way to make a local (thread-specific) instance of a random number generator if one wanted to? (never mind if this is a pointless activity or not)

PS: my "question" about Math.random being static was rhetorical.

"Greetings my friends! We are all interested in the future, for that is where you and I are going to spend the rest of our lives!" -- The Amazing Criswell
Offline ra4king

JGO Kernel


Medals: 322
Projects: 2
Exp: 4 years


I'm the King!


« Reply #16 - Posted 2011-05-22 22:36:13 »

@philfrei
All code that is loaded into RAM can go into either CPU, whether being the same class or not. The OS handles process affinity, not you, and Java rarely interferes. You don't need to worry how OS's handle processes. All you need to worry is making darn good games. Cheesy

Offline Orangy Tang

JGO Kernel


Medals: 51
Projects: 11


Monkey for a head


« Reply #17 - Posted 2011-05-23 00:24:33 »

@phifrei:  Yes, as raking shows explicitly, it's a static method (which is reentrant) that calls an (unoverrided, thread-safe) method.

WRT: Thread local randoms. Without looking at the code, I really don't see any point.
Math.random() is syncronised, so spawning loads of threads is just going to have then queue up behind each other and be slower than just keeping it all in one thread.

Personally I'd just create one Random object per thread, 'cos it's simple and obvious. ThreadLoacalRandom is probably using ThreadLocal storage, which is pretty darn slow IIRC.

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Offline ra4king

JGO Kernel


Medals: 322
Projects: 2
Exp: 4 years


I'm the King!


« Reply #18 - Posted 2011-05-23 02:46:23 »

@phifrei:  Yes, as raking shows explicitly, it's a static method (which is reentrant) that calls an (unoverrided, thread-safe) method.

WRT: Thread local randoms. Without looking at the code, I really don't see any point.
Math.random() is syncronised, so spawning loads of threads is just going to have then queue up behind each other and be slower than just keeping it all in one thread.
Math.random() is not synchronized. Neither is Random.

Offline Orangy Tang

JGO Kernel


Medals: 51
Projects: 11


Monkey for a head


« Reply #19 - Posted 2011-05-23 02:56:24 »

@phifrei:  Yes, as raking shows explicitly, it's a static method (which is reentrant) that calls an (unoverrided, thread-safe) method.

WRT: Thread local randoms. Without looking at the code, I really don't see any point.
Math.random() is syncronised, so spawning loads of threads is just going to have then queue up behind each other and be slower than just keeping it all in one thread.
Math.random() is not synchronized. Neither is Random.

javadoc/Math.random()

Quote
This method is properly synchronized to allow correct use by more than one thread. However, if many threads need to generate pseudorandom numbers at a great rate, it may reduce contention for each thread to have its own pseudorandom-number generator.

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Offline ra4king

JGO Kernel


Medals: 322
Projects: 2
Exp: 4 years


I'm the King!


« Reply #20 - Posted 2011-05-23 03:11:08 »

Yes they have accounted for synchronization by using java.util.concurrent.atomic.AtomicLong, which is a synchronized version of Long, to store the seed, but they didn't explicitly make Math.random and Random "synchronized".

Offline Captain Awesome

Junior Member


Medals: 2


Hi


« Reply #21 - Posted 2011-05-23 09:27:39 »

Math holds 1 instance of Random. Here is the code inside Math.random:
1  
2  
3  
4  
5  
6  
7  
8  
9  
public static double random() {
    if(randomNumberGenerator == null) initRNG();
    return randomNumberGenerator.nextDouble();
}

private static synchronized void initRNG() {
    if(randomNumberGenerator == null)
        randomNumberGenerator = new Random();
}


Does anyone know why Math.random() uses double-checked locking? I read that dcl can cause very unexpected behaviours (like assigning a reference to an object before the constructor has run)
Offline Orangy Tang

JGO Kernel


Medals: 51
Projects: 11


Monkey for a head


« Reply #22 - Posted 2011-05-23 10:47:16 »

Yes they have accounted for synchronization by using java.util.concurrent.atomic.AtomicLong, which is a synchronized version of Long, to store the seed, but they didn't explicitly make Math.random and Random "synchronized".
Now you're just being obtuse. Syncronised means more than just using the 'syncronised' keyword.

Regardless, there's thread-contention structures within it that make inadvisable to call repeatedly from multiple threads. The double-checked-locking is suspicious as well. Which is why it'd be a much better idea to just use a Random object per-thread.

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Offline cylab

JGO Knight


Medals: 34



« Reply #23 - Posted 2011-05-23 10:57:29 »

Math holds 1 instance of Random. Here is the code inside Math.random:
1  
2  
3  
4  
5  
6  
7  
8  
9  
public static double random() {
    if(randomNumberGenerator == null) initRNG();
    return randomNumberGenerator.nextDouble();
}

private static synchronized void initRNG() {
    if(randomNumberGenerator == null)
        randomNumberGenerator = new Random();
}


Does anyone know why Math.random() uses double-checked locking? I read that dcl can cause very unexpected behaviours (like assigning a reference to an object before the constructor has run)

DCL is OK on newer VMs as long as the variable is declared volatile. There is some discussion though, if volatile DCL has any benefits over straight forward synchronized lazy instantiation.

Mathias - I Know What [you] Did Last Summer!
Online Roquen
« Reply #24 - Posted 2011-05-23 12:51:32 »

Now you're just being obtuse. Syncronised means more than just using the 'syncronised' keyword.

Not quite.  The atomic primitive operations will simply to be promoted to a single CPU opcode.  Where a synchronized block is (minimally) something like: zero counter, set reg to lock-mutex value, atomic swap, did I get the lock, if no do stuff, if yes do the block, set reg to unlock-mutex value and atomic swap.  So the real cost of Atomic ops is that if the data is loaded into the cache of some other core when a second one modifies it, then the memory controller needs to invalidate the cached info in the first and reload (after whatever write-back scheme is done from the operation triggered by the second.)  Of course the same applies to accessing the mutex memory location for the synchronized block...ugly.

My suggestion is to avoid the problem.  Don't use a global number generator (or very rarely).  Then you don't need to worry about contention.
Offline ra4king

JGO Kernel


Medals: 322
Projects: 2
Exp: 4 years


I'm the King!


« Reply #25 - Posted 2011-05-23 16:41:27 »

What is double-checked locking?

Offline Captain Awesome

Junior Member


Medals: 2


Hi


« Reply #26 - Posted 2011-05-23 17:19:05 »

What is double-checked locking?

Short story: Using lazy initialization to init a field by checking if the field is null twice (first one is outside a synchronized block, the second is inside a synchronized block) to make sure the field only gets initialized once. Kinda like this:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
// Broken multithreaded version
// "Double-Checked Locking" idiom
class Foo {
    private Helper helper = null;
    public Helper getHelper() {
        if (helper == null) {
            synchronized(this) {
                if (helper == null) {
                    helper = new Helper();
                }
            }
        }
        return helper;
    }

    // other functions and members...
}


It may seem to be correct code, but that code can go very wrong since the compiler can re-arrange instructions.
Making the helper field volatile will solve this problem though.

Longer story: Wikipedia and Google
Offline ra4king

JGO Kernel


Medals: 322
Projects: 2
Exp: 4 years


I'm the King!


« Reply #27 - Posted 2011-05-23 18:25:45 »

What could go wrong with that? And the Random object inside Math isn't volatile :/

Online Roquen
« Reply #28 - Posted 2011-05-23 20:26:39 »

In the math case it does really matter.  If more then one happens to be allocated, all but one will end up being collected.

What can go wrong is that since helper isn't volatile, then compiler may remove the second compare to null, since by static analysis it's already be "shown" to be null in the first.
Offline cylab

JGO Knight


Medals: 34



« Reply #29 - Posted 2011-05-24 10:28:48 »

Also the newer VMs memory model ensure that volatile variables are always accessed via their real memory location (or something like that) to prevent multithreaded code to work on the CPU-cached value, which could be different in multicore systems.

Mathias - I Know What [you] Did Last Summer!
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

theagentd (6 views)
2014-04-24 23:00:44

xsi3rr4x (83 views)
2014-04-15 18:08:23

BurntPizza (75 views)
2014-04-15 03:46:01

UprightPath (86 views)
2014-04-14 17:39:50

UprightPath (69 views)
2014-04-14 17:35:47

Porlus (86 views)
2014-04-14 15:48:38

tom_mai78101 (109 views)
2014-04-10 04:04:31

BurntPizza (169 views)
2014-04-08 23:06:04

tom_mai78101 (265 views)
2014-04-05 13:34:39

trollwarrior1 (217 views)
2014-04-04 12:06:45
List of Learning Resources
by SHC
2014-04-18 03:17:39

List of Learning Resources
by Longarmx
2014-04-08 03:14:44

Good Examples
by matheus23
2014-04-05 13:51:37

Good Examples
by Grunnt
2014-04-03 15:48:46

Good Examples
by Grunnt
2014-04-03 15:48:37

Good Examples
by matheus23
2014-04-01 18:40:51

Good Examples
by matheus23
2014-04-01 18:40:34

Anonymous/Local/Inner class gotchas
by Roquen
2014-03-11 15:22:30
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!