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 tr开发者_如何学Pythonied initializing the transient arraylist in the no args constructor, which did nothing to help. What do I do? Thanks.
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.
You can't iterate with foreach statement and modify your table.
Try to use
for (int i =0;i<arra.length;i++)
instead.
Copy the ArrayList
to a new instance (shallow copy with new ArrayList<>()
and serialize that.
Use the Iterator if you are traversing through the collection and concurrently modifying it.
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.
精彩评论