This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I have a collection which contains large number of objects and takes longer time to iterate.
I am new to java and just wondering how I can speed up the process.
Can I split the collection into 2 and iterate them in 2 treads? How can I do that?
Can I have two iterators for same collection to iterate from different locations?
Can someone help with an example on how to speed up my program?
If you have a List you can use the subList method to get a portion of the List, which you can then iterate over. If you have a SortedSet you can use the headSet, subSet and tailSet methods to do something similar.
Note that you need to take care of synchronization when using the same collection from multiple threads. Even if you use one of the above methods, they are still connected to the original List / SortedSet. Just iterating over them shouldn't be a problem, but you'll run into problems (ranging from ConcurrentModificationExceptions to corruption of the collection internals) if you attempt to modify it without taking the proper precautions.
ronald dsouza wrote:@Stephan: I am issuing a db query and it returns me a very large collection which I need to iterate and do processing on each item in collection.
Are you aware that splitting the process over multiple threads can actually make it perform worse? If you have more threads than available processor cores (use the result of Runtime.getRuntime().availableProcessors()) the threads will have a lot more overhead because of context switching - pausing one thread, then active another. Just because you make your process use multiple threads doesn't mean that everything is done concurrently. In the end a processor core can only do one thing at a time.