I'm aware that the incrementing going on in the below code is not atomic. I'd like the incrementing, insertion into blocking queue and printing value of counter all together be an atomic operation. I'm aware of the atomic int but I'm trying to get this to work using synchronization for learning purposes.
int counter = 0;
BlockingQueue<Integer> numbers = new ArrayBlockingQueue<Integer>(100);
while(true) {
numbers.put(counter++);
System.out.println("Inserted new number: " + counter);
}
... // other code that may take things off the numbers queue..
What if I define a synchronized method called increment() that increments, prints and returns and pass that to numbers.put(increment());
? In that situation, would incrementing, printing and inserting into the blocking queue together be one atomic operation?