Reputation: 5959
My program updates several hundred objects stored in an ArrayList about one hundred times per second. I've implemented Java's built in serialization, and it works well except when an attempt to serialize is made when the objects are going at it, in which case I may have to serialize a half dozen times before it works (each failed attempt throws an exception). I tried marking the arraylist as transient, but then when I loaded the serialization file, a null pointer exception is thrown. So I tried initializing the transient arraylist in the no args constructor, which did nothing to help. What do I do? Thanks.
Upvotes: 1
Views: 2196
Reputation: 4706
Assuming you really don't want or need the list contents serialised declare your list member:
private transient final List<?> things = new ArrayList<Object>();
You will always have a non-null list to work with.
That being said, from the sound of it your updates to the list itself may need to be thought about regarding other thread-safety issues such data-races and visibility issues.
Upvotes: 0
Reputation: 365
Use the Iterator if you are traversing through the collection and concurrently modifying it.
Upvotes: 0
Reputation: 72039
First make sure you've synchronized access to your ArrayList
, e.g. when you initialize it:
List<String> list = Collections.synchronizedList(new ArrayList<String>());
When you need to serialize it, grab a copy that will be consistent due to the synchronization:
List<String> copy = new ArrayList<String>(list);
Now you can safely serialize out this copy without blocking access to the primary list.
Upvotes: 4
Reputation: 23169
Copy the ArrayList
to a new instance (shallow copy with new ArrayList<>()
and serialize that.
Upvotes: 0
Reputation: 1615
You can't iterate with foreach statement and modify your table.
Try to use
for (int i =0;i<arra.length;i++)
instead.
Upvotes: 0