I have two threads, each has its own counter: thread A has counterA, thread B has counterB. Each thread has to use both counters: thread A has to use counterA and counterB, also thread B has to use both. I am using AtomicInteger and to share the counters between the two threads I am passing them as arguments to the threads and each thread stores the two counters in private fields.
// ...
AtomicInteger counterA = new AtomicInteger(0);
AtomicInteger counterB = new AtomicInteger(0);
Thread tA = new Thread(new RunnableA(counterA, counterB));
Thread tB = new Thread(new RunnableB(counterA, counterB));
// ... in the constructor of RunnableA ...
RunnableA(AtomicInteger counterA, AtomicInteger counterB) {
this.counterA = counterA;
this.counterB = counterB;
}
//...
// The same for RunnableB
Is this a safe publishing of the two counters? Safe-publishing is necessary because a reference to an object is not safe enough to share the object between threads. How can I achieve safe-publishing in this case?
Thanks in advance.