How to declare array elements volatile in Java?

前端 未结 4 982
别那么骄傲
别那么骄傲 2020-12-02 23:02

Is there a way to declare array elements volatile in Java? I.e.

volatile int[] a = new int[10];

declares the array referen

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 23:31

    How about this:

    static class Cell {
            volatile T elem;
        }
    
    private Cell[] alloc(int size){
            Cell[] cells = (Cell[]) (new Cell[size]);
            return cells;
        }
    
     volatile Cell[] arr;
     Cell[] newarr = alloc(16);
     for (int i = 0; i < newarr.length; i++) {
          newarr[i] = new Cell<>();
     }
     arr = newarr;
    

    the cells make the content volatile too. also I assign the new array to the volatile one only after pre allocating the cells... there's the trade off of the Cell extra memory, but it's manageable

提交回复
热议问题