Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronize on int shouldn't be necessairy, should it?

 
Andre Timmer
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

Briefly: each thread can have its own memory cache of the shared variable. That cache may only be updated at a "memory barrier", which synchronization provides. So whenever two threads will both use the value of a single variable, access to that variable should be synchronized. Otherwise each thread may work on its own "local copy" of the shared variable.

Note also that stop() is deprecated for a reason: it's dangerous. In particular, it doesn't guarantee that those caches will be flushed; changes made to the shared variable may thus never take effect.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm also not sure that "++" and "--" are guaranteed to be atomic operations.

Moving to Threads and Synchronization...
 
Henry Wong
author
Marshal
Pie
Posts: 20997
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ernest Friedman-Hill:

Note also that stop() is deprecated for a reason: it's dangerous. In particular, it doesn't guarantee that those caches will be flushed; changes made to the shared variable may thus never take effect.


stop() accomplishes the thread stop by forcing an unrolling of the stack via a ThreadDeath object. Unfortunately, if the thread is not ready for it, (and you can read that to mean anything you want) two dangerous things can happen. Synchronization locks can be freed at locations where it is not acceptable. Data variables may be left in a state that is not expected to happen, due to an unexpected exit.

This can lead to data corruption, unexpected states / conditions, deadlock, etc.

Henry
 
Henry Wong
author
Marshal
Pie
Posts: 20997
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ilja Preuss:
I'm also not sure that "++" and "--" are guaranteed to be atomic operations.


"++" is syntactic sugar for a load, increment, and store. It is *not* atomic.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic