10

I am relatively new java. I am trying understand what are the usage of classes in the package:

java.util.concurrent.atomic

I tried to understand the javaDoc for this package to get a grasp of it. But could'nt really make any sense out of it to when I should use these classes. Can someone give examples and more descriptions in simple words? thx

Hossein
  • 40,161
  • 57
  • 141
  • 175

1 Answers1

14

Consider 10 threads are incrementing int i (initialized at 0) and outputting the value the console. You can get something like this:

1
2
2
3
3
5
6
6
8
10

AtomicInteger, for example, ensures that each thread can increment or decrement the value atomically, ensuring that the write operation happens in a synchronized manner, and for 10 threads, the output would always be:

1
2
3
4
5
6
7
8
9
10
SiN
  • 3,704
  • 2
  • 31
  • 36
  • 2
    Why do you skip from 3 to 5, and from 6 to 8 in your first example? Shouldn't 2 threads read a value at the same time and write the same value? – Pavel Mar 08 '18 at 14:14