How to have an array of volatile booleans in Java

2019-08-18 01:52发布

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.

2条回答
别忘想泡老子
2楼-- · 2019-08-18 02:23

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.

查看更多
神经病院院长
3楼-- · 2019-08-18 02:35

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[]?

查看更多
登录 后发表回答