How to have an array of volatile booleans in Java and not a volatile array of booleans?

落爺英雄遲暮 提交于 2019-12-13 20:48:53

问题


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.


回答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.




回答2:


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



来源:https://stackoverflow.com/questions/21958926/how-to-have-an-array-of-volatile-booleans-in-java-and-not-a-volatile-array-of-bo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!