Conversion of AtomicInteger to int

I wrote a thread and for memory synchronization I have to use Atomicinteger. Here is my code:

public class NewClass implements Runnable {

public double rr;
public double rmse_new;
public double rmse_newT;
private int k;
private int[][] Xdisc;

public NewClass(int Xdisc[][], double[][] pat_cand, int k, double[][] Yresid, double[][] Xresid) {

    this.k = k;
    this.Xdisc = Xdisc;
}

@Override
public void run() {
    final AtomicInteger q = new AtomicInteger(0);
    q.set(0);
    while (true) {
        if (q.incrementAndGet() >= Xdisc.length) {
            break;

            Integer[] temp_X;
            temp_X = new Integer[Xdisc[0].length];
            for (int s = 0; s < Xdisc[0].length; s++) {
                temp_X[s] = Xdisc[q][s];
            }
        }
    }
}
}

the problem is that q is the row index of a 2D array Xdisc (in main class) and apparently should be integer but in NewClass, q is AtomicInteger. Therefore I got this error:

incompatible types
required: int
found: AtomicInteger

in this line

temp_X[s] = Xdisc[q][s];

and I even tried

temp_X[s] = Xdisc[(int)q][s];

and got this error:

inconvertible types

Is there anyway to convert AtomicInteger to int?

Jon Skeet
people
quotationmark

If you're trying to use the same value throughout the loop, just use the return value of incrementAndGet():

int index = q.incrementAndGet();
if (index >= Xdisc.length) {
    break;
} // I'm assuming you meant there to be a brace here...

Integer[] temp_X;
temp_X = new Integer[Xdisc[0].length];
for (int s = 0; s < Xdisc[0].length; s++) {
    temp_X[s] = Xdisc[index][s];
}

If you want the absolute latest value, use get().

people

See more on this question at Stackoverflow