0

Currently this seems to be working but maybe one day it'll bug :

I have a 2 dimensional array of boolean, those boolean represent the state of various objects (if they are ready or not to be processed)

A thread is running and making those objects, once an object is made it's boolean is set to "true" (making an object takes up to 20ms).

my question is :

Can I read (only read) this array while the thread is doing its magic? What would happend if the thread was to write true while my method was reading it?

thanks.

Heetola
  • 5,791
  • 7
  • 30
  • 45
  • I think it really depends on how 'fresh' you expect your reads to be. I was trying to come up with an explanation, but these two posts together might lead to a solution for your particular situation. http://stackoverflow.com/questions/2236184/how-to-declare-array-elements-volatile-in-java http://stackoverflow.com/questions/5173614/java-volatile-array – Jason Dunkelberger Jul 20 '12 at 16:34

2 Answers2

2

Writes to boolean are atomic so you won't see any inconsistencies. This is not the case for long and double.

The worst thing than can happen to you is visibility. Visibility problems occur when one thread updated given variable but other threads don't see that change immediately (or never).

In order to make sure all threads see the same, most up-to-date value, you must use some sort of synchronization or volatile fields.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • Nice, well in my case I don't think I'll ever see invonsistencies, There is only one thread, his job is to load data from the disk into the RAM. The main program loop is checking each cycle if wich block of data is ready or not to be used. – Heetola Jul 20 '12 at 16:58
  • Do you know of a strategy to make an array of volatile booleans? Is it necessary to have the overhead of a wrapper class? – snapfractalpop Oct 03 '12 at 00:46
  • @snapfractalpop: please open another question if such doesn't already exist. – Tomasz Nurkiewicz Oct 03 '12 at 06:52
1

Can I read (only read) this array while the thread is doing its magic? What would happend if the thread was to write true while my method was reading it?

Yes you can read it just fine, if you try an write to it, you may find yourself in a sticky situation. As for the second question, quite simply, that's impossible. You can't be reading that index at the exact same moment it is changing. It will either wait until the write is finished it read whatever is there just before the write.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
Rob Wagner
  • 4,391
  • 15
  • 24