views:

56

answers:

3

i have a (perhaps stupid) question:

im using 2 threads, one is writing floats and one is reading this floats permanently. my question is, what could happen worse when i dont synchronize them? it would be no problem if some of the values would not be correct because they switch just a little every write operation. im running the application this way at the moment and dont have any problems so i want to know what could happen worse?

a read/write conflict would cause a number like 12345 which is written to 54321 and red at the same time appear for example as 54345 ? or could happen something worse? (i dont want to use synchronization to keep the code as fast as possible)

A: 

If one thread is writing to a particular float and changes the value from 'a' to 'b', another thread reading the same float will only see either 'a' or 'b', never a third value.

As for any other potential logic problems your app may experience, it is impossible to answer this without knowing more about your app.

Jim Blackler
Note that your first point is true for floats, but not necessarily other data types such as `double` or `long`. Writes to these types of variables are not guaranteed to be atomic.
Mike Daniels
Interesting, I didn't know that.
Jim Blackler
...unless they're marked "volatile". The JLS guarantees that reads and writes to volatile longs and doubles are atomic.
fadden
+3  A: 

The worst that could happen is that your reader thread never sees anything your writer thread has written. There is no guarantee that memory written to by one thread will ever be seen by another thread without some form of synchronization.

Mike Daniels
thanks for your info:)but why is it that way? does the position of the data in the memory change, when its rewritten?
Sponge
@Sponge: Threads might have their own local copies of updated variables. Synchronization, in addition to merely preventing race conditions, also guarantees that any thread-local copies of data are made visible to every other thread.
Mike Daniels
A: 

Worst case is that your users find you application is errant because it does not behave properly due to concurrency issues.

Uncontested locks do not add much overhead. You should always write an application correctly first and then optimize only after running metrics which indicate where you're problem areas are. I'd wager that a lot of your application code is likely to be the source of performance issues rather than some basic synchronization.

Tim Bender