The java.util.List provides an interface for holding collections of objects that do not necessarily need to be unique. The ordering of elements does not matter.
Similarly, IList implements a distributed version of Java List. It provides similar functions: add, forEach, etc.
All the data which is present in IList is stored/present on a single JVM. Data is still accessible to all the JVMs, but the list cannot be scaled beyond a single machine/JVM.
The list supports synchronous backup as well as asynchronous backup. Synchronous backup ensures that even if the JVM holding the list goes down, all the elements would be preserved and available from the backup.
Let’s look at an example of the useful functions.
Adding elements and reading elements
Let’s execute the following code on 2 JVMs. The producer code on one and consumer code on the other.
Example
The first piece is the producer code which creates a list and adds items to it.
public static void main(String... args) throws IOException, InterruptedException {
//initialize hazelcast instance
HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();
// create a list
IList<String> hzFruits = hazelcast.getList("fruits");
hzFruits.add("Mango");
hzFruits.add("Apple");
hzFruits.add("Banana");
// adding an existing fruit
System.out.println(hzFruits.add("Apple"));
System.out.println("Size of list:" + hzFruits.size());
System.exit(0);
}
The second piece is of consumer code which reads the list elements.
public static void main(String... args) throws IOException, InterruptedException {
//initialize hazelcast instance
HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();
// create a list
IList<String> hzFruits = hazelcast.getList("fruits");
Thread.sleep(2000);
hzFruits.forEach(System.out::println);
System.exit(0);
}
Output
The output for the code for the producer shows that it is not able to add an existing element.
true
4
The output for the code for the consumer prints the list size and the fruits are in the expected order.
4
Mango
Apple
Banana
Apple
Useful Methods
Sr.No | Function Name & Description |
1 | add(Type element) Add element to the list |
2 | remove(Type element) Remove element from the list |
3 | size() Return the count of elements in the list |
4 | contains(Type element) Return if the element is present |
5 | getPartitionKey() Return the partition key which holds the list |
6 | addItemListener(ItemListener<Type>listener, value) Notifies the subscriber of an element being removed/added/modified in the list. |