So I want an array with 10 volatile booleans, not a volatile array with 10 booleans. It probably does not even make sense to have a volatile array reference, correct me if I am wrong.
Asked
Active
Viewed 376 times
0
-
And why would you want an array of volatile booleans? – Aman Agnihotri Feb 22 '14 at 19:04
2 Answers
1
If it's only 10 and is always 10, you could simply write:
private volatile boolean b1, b2, ..., b10;
A possibly cleaner way would be to use an AtomicIntegerArray(10)
and map between integers and booleans (0=false, 1=true).
You should clarify the reason why you need 10 volatile booleans: there may be a better way.

assylias
- 321,522
- 82
- 660
- 783
-
10 was just an example. I would be needing N. But if we give it a thought we conclude that this is worthless. I can just use AtomicBoolean[], right? – JohnPristine Feb 22 '14 at 19:51
-
Yes you could have a `private volatile AtomicBoolean[]` so both the array and its components are volatile. – assylias Feb 22 '14 at 19:55
-
1@John Since you probably don't want to ever replace the array itself, better make it `final` and non-volatile. As long as you initialize it in the constructor that's thread-safe too. – Voo Feb 22 '14 at 20:27
1
I believe the only way is to have a AtomicBoolean[] or an AtomicIntegerArray. Then they do not need to be volatile. Its elements will be.
If you want more fun, check this question: Which is "better". AtomicIntegerArray (1/0 as true/false) versus AtomicBoolean[]?

Community
- 1
- 1

JohnPristine
- 3,485
- 5
- 30
- 49