This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.

Reading Head First Java, 2nd Edition (0596009208), Chapter 15, pp 514. I adapted their code to include synchronized to solve the "lost update" problem:

I thought the output would increase, instead, it decreases (as shown in red), then increases:

D:\JavaJava>java TestSyncTest
balance is 1
balance is 3
balance is 4
balance is 5
balance is 6
balance is 7
balance is 8
balance is 9
balance is 2
balance is 11
balance is 12
balance is 13
balance is 14
balance is 15
balance is 16
balance is 17
balance is 18
balance is 19
balance is 20
balance is 21
balance is 22
balance is 10
balance is 24
balance is 25
balance is 26
balance is 27
balance is 28
balance is 29
balance is 30
balance is 31
balance is 32
balance is 33
balance is 34
balance is 35
balance is 36
balance is 37
balance is 38
balance is 39
balance is 40
balance is 41
balance is 42
balance is 43
balance is 44
balance is 45
balance is 46
balance is 47
balance is 48
balance is 49
balance is 50
balance is 51
balance is 52
balance is 53
balance is 54
balance is 55
balance is 56
balance is 57
balance is 58
balance is 59
balance is 60
balance is 61
balance is 62
balance is 63
balance is 64
balance is 23
balance is 65
balance is 66
balance is 67
balance is 68
balance is 69
balance is 70
balance is 71
balance is 72
balance is 73
balance is 74
balance is 75
balance is 76
balance is 77
balance is 78
balance is 79
balance is 80
balance is 81
balance is 82
balance is 83
balance is 84
balance is 85
balance is 86
balance is 87
balance is 88
balance is 89
balance is 90
balance is 91
balance is 92
balance is 93
balance is 94
balance is 95
balance is 96
balance is 97
balance is 98
balance is 99
balance is 100

Sandra Bachan wrote:Reading Head First Java, 2nd Edition (0596009208), Chapter 15, pp 514. I adapted their code to include synchronized to solve the "lost update" problem:

Believe it or not, you did solve the "lost update" problem. If you really had a lost update, then the final value would not be 100.

What is happening is... There is no coordination between the two threads, in printing the results, so you are seeing the results being printed out of order.