Tuesday 15 March 2011

java - get the synchronisation right -


I did a little test, because I wanted to store an array (or some type of list) Threads in

My main orbit:

  Package main; Import java.util.Timer; Import java.util.TimerTask; Public Class Main {Private Last Fixed Object Lock = New Object (); Public stationary zero main (string [] args) {timer timer = new timer (); Timer.timeAtFixedRate (new timer cookies) {@Override Public Zero Run () {Synchronize (Lock) {Values.incrementValues ​​();}}}, 1000, 1000); Timer timer 1 = new timer (); Timer1.scheduleAtFixedRate (New TimerTask) {@Override Public Zero Run (synchronize (lock) {values.addValue (0);}}}, 1000, 1000); Timer timer 2 = new timer (); Timer 2.scheduleAtFixedRate (new timer cookies) {@Override Public Zero Run () {Synchronize (Lock) {values.printValues ​​();}}}, 1000, 1000); }}  

And this is the class in which I store the array: the package main;

  public class values ​​(static int [] value = new int [1]; Private last fixed object lock = new object (); Public static zero growth value () {synchronize (lock) {for (int i = 0; i & lt; values.length; i ++) {value [i] ++; }}} Public static Zero addValue (int e) {synchronize (lock) {int [] temp = values; Value = new int [temp.length + 1]; For (int i = 0; i  

I should get the output like a row of rows: 10 9 8 7 6 5 4 3 2 1 0

But instead of me 21 21 1 9 18 17 16 15 15 14 13 11 10 9 7 6 6 5 4 2 1 0

I think it should be directly in front of me, but I can not find it.

/ div>

You guarantee to execute two threads in synchronization but do not guarantee execution order Are there.

Therefore, in the event of a increase value and addValue will be in the race condition. You have duplicate variables because addValue is sometimes executed before increment value

if you guarantee sequential order without any duplicates You want to apply a gate that incrementValues ​​ and addValue are executed in the proper order.

BTW: I think the blocks synchronized in main class are unnecessary because you are already locking in the value class.


No comments:

Post a Comment