I have an integer ArrayList of 50 numbers where each number is an ID . From the main program i want to read the 50 numbers in a loop and and for each id i want to create a thread.There a global ArrayList of String . Each thread should insert to the String ArrayList its ID . I paste the code below .So at the end the String ArrayList should also be of size 50 with all the IDs inserted atmost once . However i am finding that not all 50 are getting processed .At times 42,at times 43 or 48 and these numbers are varying inconsistently.
Can someone please help where i am going wrong .
well come to code ranch.
Synchronized code should be in a common place where multiple threads can access but you have synchronized the addElement method which is in the thread it self and it will be only accessed by the thread itself it is not visible to other threads. This will not prevent from other threads from making a data race on the myList they will store data in the same list position, that's why its actually finishing with lesser than number 49 and 50 elements in the array list.
you can do two things
change myList to a collection from the concurrent API and remove your synchronized key word from the addElement , any way its not synchronizing any thing.
move the addElement to the another class just add it to the ThreadPoolTest.class as a static method or create a singleton class and the method synchronized.
but i prefer the first one.