File tree Expand file tree Collapse file tree 3 files changed +97
-0
lines changed
java-synchronization-and-locks/src Expand file tree Collapse file tree 3 files changed +97
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .concurrent .ExecutorService ;
2
+ import java .util .concurrent .Executors ;
3
+
4
+ /**
5
+ * Created by rajeevkumarsingh on 11/05/17.
6
+ */
7
+ class Counter {
8
+ private int count = 0 ;
9
+
10
+ public void increment () {
11
+ count = count + 1 ;
12
+ }
13
+
14
+ public int getCount () {
15
+ return count ;
16
+ }
17
+ }
18
+
19
+ public class RaceConditionExample {
20
+
21
+ public static void main (String [] args ) {
22
+ ExecutorService executorService = Executors .newFixedThreadPool (10 );
23
+
24
+ Counter counter = new Counter ();
25
+
26
+ for (int i = 0 ; i < 1000 ; i ++) {
27
+ executorService .submit (() -> counter .increment ());
28
+ }
29
+
30
+ System .out .println ("Final count is : " + counter .getCount ());
31
+ }
32
+ }
Original file line number Diff line number Diff line change
1
+ import java .util .concurrent .ExecutorService ;
2
+ import java .util .concurrent .Executors ;
3
+
4
+ /**
5
+ * Created by rajeevkumarsingh on 11/05/17.
6
+ */
7
+ class FineGrainedSynchronizedCounter {
8
+ private int count = 0 ;
9
+
10
+ public void increment () {
11
+ // Synchronized Block
12
+ synchronized (this ) {
13
+ count = count + 1 ;
14
+ }
15
+ }
16
+
17
+ public int getCount () {
18
+ return count ;
19
+ }
20
+ }
21
+
22
+ public class SynchronizedBlockExample {
23
+ public static void main (String [] args ) {
24
+ ExecutorService executorService = Executors .newFixedThreadPool (10 );
25
+ FineGrainedSynchronizedCounter counter = new FineGrainedSynchronizedCounter ();
26
+
27
+ for (int i = 0 ; i < 1000 ; i ++) {
28
+ executorService .submit (() -> counter .increment ());
29
+ }
30
+
31
+ System .out .println ("Final count is " + counter .getCount ());
32
+ }
33
+ }
Original file line number Diff line number Diff line change
1
+ import java .util .concurrent .ExecutorService ;
2
+ import java .util .concurrent .Executors ;
3
+
4
+ /**
5
+ * Created by rajeevkumarsingh on 11/05/17.
6
+ */
7
+ class SynchronizedCounter {
8
+ private int count = 0 ;
9
+
10
+ // Synchronized Method
11
+ public synchronized void increment () {
12
+ count = count + 1 ;
13
+ }
14
+
15
+ public int getCount () {
16
+ return count ;
17
+ }
18
+ }
19
+
20
+ public class SynchronizedMethodExample {
21
+ public static void main (String [] args ) {
22
+ ExecutorService executorService = Executors .newFixedThreadPool (10 );
23
+
24
+ SynchronizedCounter synchronizedCounter = new SynchronizedCounter ();
25
+
26
+ for (int i = 0 ; i < 1000 ; i ++) {
27
+ executorService .submit (() -> synchronizedCounter .increment ());
28
+ }
29
+
30
+ System .out .println ("Final count is : " + synchronizedCounter .getCount ());
31
+ }
32
+ }
You can’t perform that action at this time.
0 commit comments