The Problem
Can you figure it out what's the issue in the following code?
@Cacheable(key = "#appName", sync = true)
public Iterator<Message> findActiveMessages(final String appName) {}
Iterator vs Iterable
In most case we can use either Iterable or Iterator, but there is one key difference:
- if we need traverse and get the value multiple times, then we can't use Iterator.
As once you loop all the data in the iterator, the iterator points to the last position +1 and is not usable anymore. Now if we can iterator.haneNext(), it would be false; if we try to loop it again, we will get empty data.
Unless you define it as ListIterator and manually move back one by one till reach the beginning, which is inefficient and we don't usually code that way.
Takeaway
Don't use Iterator when need traverse multiple times
Don't use Iterator as cache value
Don't store Iterator in collection.
Can you figure it out what's the issue in the following code?
@Cacheable(key = "#appName", sync = true)
public Iterator<Message> findActiveMessages(final String appName) {}
Iterator vs Iterable
In most case we can use either Iterable or Iterator, but there is one key difference:
- if we need traverse and get the value multiple times, then we can't use Iterator.
As once you loop all the data in the iterator, the iterator points to the last position +1 and is not usable anymore. Now if we can iterator.haneNext(), it would be false; if we try to loop it again, we will get empty data.
Unless you define it as ListIterator and manually move back one by one till reach the beginning, which is inefficient and we don't usually code that way.
Takeaway
Don't use Iterator when need traverse multiple times
Don't use Iterator as cache value
Don't store Iterator in collection.