This is the first time I've come across something like below.
Multiple threads (inner classes that implement Runnable) sharing the data structure (instance variable of the upper class).
Work: took classes from the bin folder of the Eclipse project project, is launched on a Unix machine.
DOES NOT WORK: directly compiled src on a Unix machine and used these class files. The code compiles and then runs without errors / warnings, but one thread cannot normally access the shared resource.
PROBLEM: One thread adds items to the above shared DS. The second thread does the following ...
while(true){ if(myArrayList.size() > 0){ //do stuff }
}
The log shows that the size is updated in stream 1.
For some mystical reason, the workflow does not start if () ...
The same exact code works fine if I directly paste class files from the Eclipse bin folder.
I apologize if I missed something obvious.
code:
ArrayList<CSRequest> newCSRequests = new ArrayList<CSRequest>();
// Topic 1
private class ListeningSocketThread implements Runnable { ServerSocket listeningSocket; public void run() { try { LogUtil.log("Initiating..."); init();
}
//Thread 2 private class CSRequestResponder implements Runnable { public void run() { LogUtil.log("Initiating..."); // REACHES.. while (true) { // LogUtil.log("inside while..."); // IF NOT COMMENTED, FLOODS THE CONSOLE WITH THIS MSG... if (newCSRequests.size() > 0) { // DOES NOT PASS LogUtil.log("inside if size > 0..."); // NEVER REACHES.... try { handleNewCSRequests(); } catch (IOException e) { e.printStackTrace(); } } } } .... }
UPDATE Many thanks @maasg ...
The solution was to add synchronized (myArrayList) before checking the size in stream 2.
source share