I have a piece of code to create an object and increase the count of created objects. The code of creating object and increasing the count in guarded by an if condition checking if the count has reached the MAX number of objects. When running the code with multi-threads, the if condition could be breached (i.e. no effect) determined by the position of the line increment the count. Could this caused by Java compiler optimization? The following is the code snippets:
private BlockingQueue<WeakReference<ItemType>> items;
private final ReferenceQueue<ItemType> referenceQueue = new ReferenceQueue<ItemType>();
private final int maxSize = 10;
private final AtomicInteger numberOfCreatedObj = new AtomicInteger(0);
protected ItemType create(boolean addToCache) {
ItemType item = null;
try {
if (!hasCreatedMaxObjects()) {
// we have not reached maxSize yet.
item = getFactory().create();
// this position makes the MAX objects checking working
// Position A:
increaseCreatedObjectCount();
LOG.debug("Created new item [" + item.getId() + "]");
if (addToCache) {
LOG.debug("Add to cache the new item [" + item.getId() + "]");
addCreated(item);
}
// This position makes the MAX objects checking failed
// Position B;
//increaseCreatedObjectCount();
} else {
LOG.warn("Already reached MAX created objects " + numberOfCreatedObj.get());
}
} catch (Exception e) {
LOG.error("Error in creating a new object", e);
}
return item;
}
protected boolean hasCreatedMaxObjects() {
return getNumberOfCreatedObj().compareAndSet(getMaxSize(), getMaxSize());
}
protected void increaseCreatedObjectCount() {
getNumberOfCreatedObj().incrementAndGet();
}
protected void addCreated(ItemType item) {
items.offer(new WeakReference<ItemType>(item, referenceQueue));
}
I ran my test with 30 thread. Each thread sleeps for 100 milliseconds after getting a created object. When increaseCreatedObjectCount() is called at position A, the code work fine and there were 10 (MAX) objects created. When increaseCreatedObjectCount() is called at position B, 30 objects were created, which equals to the number of running threads.
How could I view Java compiler optimized code?
Thank you.