1

I am creating an ArrayList of objects using generics. Each thread does come calculating and stores the object in the the array list.

However when looking at the ArrayList which is static and volatile all the object attributes are set as null. My thoughts are something to do with the garbage collector removing the instances in the threads so once the threads have finished there is no reference to them.

Any help would be really helpful?

4
  • 2
    Can you post some example code? Commented Nov 22, 2014 at 23:32
  • The garbage collector never "nulls" a variable or otherwise changes an object. A value of null was either assigned explicitly or was the default. Now, using an ArrayList from multiple threads is inherently problematic - at least without the use of synchronized. Commented Nov 22, 2014 at 23:49
  • Your thoughts are wrong. Commented Nov 23, 2014 at 0:01
  • At the moment I am testing it and with in the same thread I can do topDesigns.getList().get(0).isEvaluated() . (Where getList() returns the ArrayList and isEvaluated() checks if the object has a state (value != null) and getValue() which returns the value. It returns true while in the thread but once the thread exits and returns to the main thread the value of all the objects goes to null. Commented Nov 23, 2014 at 0:02

1 Answer 1

2

The garbage collector will not remove instances1 from an array list. That is not the problem.

The problem is most likely that you are accessing and updating the array list object without proper synchronization. If you do not synchronize properly, one thread won't always see the changes made by another one.

Declaring the reference to the ArrayList object only guarantees that the threads will see the same list object reference. It makes no guarantees about what happens with the operations on the list object.


1 - Assuming that the array list is reachable when the GC runs, then all elements that have been properly added to the list will also be reachable. Nothing that is reachable will be deleted by the garbage collector. Besides, the GC won't ever reach into an object that your application can still see and change ordinary references to null.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.