In Java, we use the final keyword with variables to indicate that their values should not be modified. But, I see that you may edit the value in the constructor / methods. If the variable is static, this is another compilation fault. The code is as follows: Code: import java.util.ArrayList; import java.util.List; class Test { private final List foo; public Test() { foo = new ArrayList(); foo.add("foo"); // Modification-2 } public static void main(String[] args) { Test t = new Test(); t.foo.add("bar"); // Modification-3 System.out.println("print - " + t.foo); } } The code above is error-free. Now make the variable static: Code: private static final List foo; It is now a compilation error. How does this final work in practise?
Final does not mean immutable, you still can modify the contents of the collection. https://en.wikipedia.org/wiki/Final_(Java) What it means is: "A final variable can only be initialized once, either via an initializer or an assignment statement". You essentially can create only one instance of the object but the contents can be modified.
Make sure that you don't access to private attributes outside the actual class, add a getter and a setter. Also define a type for you collections, you don't want the runtime to assign any type it wants. Code: import java.util.ArrayList; import java.util.List; public class Test { private final List<String> fooList; public void addFoo(String foo) { this.fooList.add(foo); } public List<String> getFoo() { return fooList; } public Test() { fooList = new ArrayList<String>(); } }
I implemented immutability of my objects by using mprotect to mark the section of ram the buffer contents are stored in as read only . This only works for objects backed by native memory
You could patch the jvm to do it using the same way swap files and memory mapped files are done .. mprotect violation signals a handler to fetch the segment and then return the execution flow to the point the segmentation violation was triggered
If you want to prevent changes to the content of a Collection, see https://docs.oracle.com/en/java/jav...#unmodifiableCollection(java.util.Collection)