2626
2727import java .util .Arrays ;
2828import java .util .Objects ;
29+ import java .util .concurrent .atomic .AtomicLong ;
2930import io .nayuki .sortalgodemo .core .AbstractSortArray ;
3031
3132
@@ -44,8 +45,8 @@ final class VisualSortArray extends AbstractSortArray {
4445 private volatile boolean isDone ;
4546
4647 // Statistics
47- private volatile long comparisonCount ;
48- private volatile long swapCount ;
48+ private AtomicLong comparisonCount = new AtomicLong () ;
49+ private AtomicLong swapCount = new AtomicLong () ;
4950
5051 // Speed regulation
5152 private final double stepsPerSecond ;
@@ -68,18 +69,17 @@ public VisualSortArray(int size, double speed) {
6869 stepsPerSecond = speed ;
6970 stepsPerCheck = (int )Math .max (Math .min (stepsPerSecond * CHECK_INTERVAL_NS / 1e9 , 1_000_000 ), 1 );
7071 state = new int [size ];
71- 72- // Initialize various numbers
73- comparisonCount = 0 ;
74- swapCount = 0 ;
7572 }
7673
7774
7875 public void finishInitialization () {
7976 if (isInitialized )
8077 throw new IllegalStateException ();
8178 isInitialized = true ;
79+ 8280 isDone = false ;
81+ comparisonCount .set (0 );
82+ swapCount .set (0 );
8383
8484 stepsRemaining = stepsPerCheck ;
8585 prevCheckTimeNs = System .nanoTime ();
@@ -98,7 +98,7 @@ public int compare(int i, int j) {
9898 setElement (i , ElementState .COMPARING );
9999 setElement (j , ElementState .COMPARING );
100100 regulateSpeed ();
101- comparisonCount ++ ;
101+ comparisonCount . setOpaque ( comparisonCount . getPlain () + 1 ) ;
102102
103103 setElement (i , ElementState .ACTIVE );
104104 setElement (j , ElementState .ACTIVE );
@@ -113,7 +113,7 @@ public void swap(int i, int j) {
113113 return ;
114114 if (Thread .interrupted ())
115115 throw new StopException ();
116- swapCount ++ ;
116+ swapCount . setOpaque ( swapCount . getPlain () + 1 ) ;
117117 setElement (i , ElementState .ACTIVE );
118118 setElement (j , ElementState .ACTIVE );
119119 regulateSpeed ();
@@ -147,11 +147,11 @@ public int getState(int index) {
147147 /* After sorting */
148148
149149 public long getComparisonCount () {
150- return comparisonCount ;
150+ return comparisonCount . getOpaque () ;
151151 }
152152
153153 public long getSwapCount () {
154- return swapCount ;
154+ return swapCount . getOpaque () ;
155155 }
156156
157157
0 commit comments