Complete List of immutable JDK classes? - immutability

is there a list of de-facto immutable classes in the jdk?
technically Immutable classes include the obvious Integer, Double etc..
de-facto immutable will include for example java.lang.String - it might technically be mutable but de-facto it is not.
Also, are there Interfaces/Abstract classes which are required (as stated in the javadoc) to be immutable?
if you cannot provide a complete List, i would already be happy if you know a bunch of classes which state immutability in its javadoc..

I try to compile the list as much as I can:
java.lang.String
The wrapper classes for the primitive types:
java.lang.Integer
java.lang.Byte
java.lang.Character
java.lang.Short
java.lang.Boolean
java.lang.Long
java.lang.Double
java.lang.Float
java.lang.StackTraceElement (used in building exception stacktraces)
Most of the enum classes
java.math.BigInteger
java.math.BigDecimal
java.io.File
java.awt.Font
java.awt.BasicStroke
java.awt.Color
java.awt.GradientPaint,
java.awt.LinearGradientPaint
java.awt.RadialGradientPaint,
java.awt.Cursor
java.util.Locale
java.util.UUID
java.util.Collections
java.net.URL
java.net.URI
java.net.Inet4Address
java.net.Inet6Address
java.net.InetSocketAddress
most subclasses of java.security.Permission

You can use MutabilityDetector and feed it JARs from the JDK to enumerate most immutable classes. It's "most" because it's so strict that even the tiny bit of state change in java.lang.String is enough to make it considered mutable, but the goal is to account for this by 1.0 release.
You can download the latest JAR here: https://github.com/MutabilityDetector/MutabilityDetector/releases
Here's an example of it's use. This is what I used to get most of the immutable JDK 1.7 classes on OSX:
java -jar MutabilityDetector-0.9.5.jar -r IMMUTABLE -cp /Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home/jre/lib/rt.jar
Here's the output (slightly cleaned up):
https://gist.github.com/CalebFenton/85fc87edf64033afe110
I needed to do this for Android framework classes. The tricky part was finding a JAR with Android classes, and not just stubs which is the one included in the SDK. The good people at Robolectric make one, which you can download here: http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22android-all%22
You can see the list of immutable Android classes I use, which includes many JDK classes here:
https://github.com/CalebFenton/simplify/blob/master/smalivm/src/main/resources/immutable_classes.cfg

Classes whose object contents cannot be modified is called immutable classes. All primitive data types(Wrapper classes only) are immutable. For any class to be immutable the following needs to be done.
Make all fields private
Don't provide mutators
Ensure that methods can't be overridden by either making the class
final (Strong Immutability) or making your methods final (Weak
Immutability)
If a field isn't primitive or immutable, make a deep clone on the way
in and the way out.
Thank you

Related

Does serialization of objects with same class but different packages cause an errors in Axon?

I read a blog post and there was a sentence like this
"In Axon, there are constraints that require the package structure of the Event classes to be identical.
So even the same class, if the package is different, an error can occur."
And for this reason, he recommends using a multi-module structure.
is that true? I'm looking at the references and trying to find something like this, but I can't.
This point is indeed true, #YongD.
Axon Framework, when serializing any of your objects, will store the serialized format and the type. The serialized format that's stored most often is a byte[] of either XML or JSON. Which of the two depends on whether you have configured the XStreamSerializer or the JacksonSerializer.
So next to the serialized data, we have the type. The type, by default, would be the fully qualified class name and an optional revision number. Without the fully qualified class name, the serializer wouldn't know how to deserialize your data back into the required format. The package name is part of the FQCN, having different package names for conceptually the same class might cause issues upon deserialization.
This is why in sample projects provided by AxonIQ, you will always see all the messages belong to a core-api or api package or module. Already having this separation will allow for easier extraction of services into microservices at a later stage.

IllegalAccessError Java 8 Method reference with package visibility class [duplicate]

Error while executing below code,
Caused by: java.lang.IllegalAccessError: tried to access class
com.google.common.collect.AbstractTable from class
ImmutableTable.copyOf(listItemsToProcess.parallelStream()
.map(item ->
ProcessorInstanceProvider.getInstance()
.buildImmutableTable(item))
.collect(() -> HashBasedTable.create(),
HashBasedTable::putAll,
HashBasedTable<Integer, String,
Boolean>::putAll)
);
Error in coming on - HashBasedTable::putAll Using Oracle's 1.8 jre
This is a compiler bug, related reports are
JDK-8152643: “Javac compiles method reference that allows results in an IllegalAccessError”
JDK-8059632: “Method reference compilation uses incorrect qualifying type”
Note that the first report has the status “Fixed in 8u102”, so downloading JDK8u102 could solve the issue. Of course, when using a compiler other than javac, e.g. ECJ, you have to ensure that that compiler is up to date as well.
In either case, you have to recompile the source code, as it is a compiler issue. But then, the compiled code should even work with older JREs.
To explain the issue, normally, invocations should be encoded into the byte code using the compile-time type of the receiver (or the explicit type in case of static methods), regardless of the declaring type of the actual method implementation. So if you have a public class A inheriting the public method foo from the non-public class B, an invocation of A.foo should be encoded as A.foo rather than B.foo. For ordinary invocations, the compilers work that way, but for method references, javac (and afaik also older versions of ECJ) failed to do that correctly. So when encountering a class trying to access B.foo directly without having access to B, an IllegalAccessError is thrown.
It works when using a lambda expression instead, as then, the invocation is compiled into an ordinary invocation instruction, for which the compiler works correctly, within a synthetic method and a reference to that synthetic method is used when constructing an instance of the functional interface at runtime. Since the synthetic method recides within the same class, it’s always accessible.
AbstractTable was introduced in Guava version 15. Take a look at your classpath configuration; you're probably using an earlier library version at runtime.
Interesting, i replaced method references with Lambda expression and it worked.
ImmutableTable.copyOf(itemList.parallelStream()
.map(item ->
ProcessorInstanceProvider.get()
.buildImmutableTable(item))
.collect(() -> HashBasedTable.create(),
(a, b) -> a.putAll(b),
(a, b) -> a.putAll(b))
);

Interface attributes not automatically replicated to class in UML class diagram in Visual Studio

In Visual Studio, I've created a UML class diagram with a class that realises an interface containing an attribute and an operation as thus:
The operation is automatically replicated to the class, but not the attribute. The MSDN guidelines indicate this behaviour:
When you create a realization connector, the operations of the interface are automatically replicated in the realizing class. If you add new operations to an interface, they are replicated in its realizing classes.
However, this seems counterintuitive to their statement just beforehand, namely:
Realization means that a class implements the attributes and operations specified by the interface.
I'm sure there must be a good technical reason for this (some OO concept like polymorphism or abstraction), but I can't think why it discerns between attributes and operations in this way.
Can anyone give me some insight into this, and perhaps what I should do to get round it (do I add the attributes to the class manually in UML?), as it's resulting in generated code that doesn't compile?
While I don't know for sure, I'd imagine it is because in C# interfaces cannot contain fields, only methods. Having attributes on an Interface therefore doesn't make sense.
Interfaces can contain properties, but these just get compiled to PropType get_PropName() and void set_PropName(PropType value). (Fun fact, trying to declare those methods yourself will generate a compiler error.)
Unfortunately, there is not a nice "out of the box" way of defining properties in UML class diagrams, as they are a language specific feature. I think you have to define a custom stereotype and the templates to generate the code accordingly - faff.

Java 8 doesn't provide the same solution to allow multiple inheritance which they gave to solve interface default methods

Problem:
We know that Java doesn’t allow to extend multiple classes because it would result in the Diamond Problem where the compiler could’t decide which superclass method to use. With interface default methods the Diamond Problem were introduction in Java 8. That is, because if a class implements two interfaces, each defining the same default method, and the implementing class doesn’t override the common default method, the compiler couldn’t decide which implementation to chose.
Solution:
Java 8 requires to provide an implementation for default methods implemented by more than one interface. So if a class would implement both interfaces mentioned above, it would have to provide an implementation for the common default method. Otherwise the compiler would throw a compile time error.
Question:
Why is this solution not applicable for multiple class inheritance, by overriding common methods introduced by child class?
You didn’t understand the Diamond Problem correctly (and granted, the current state of the Wikipedia article doesn’t explain it sufficiently). As shown in this graphic,
the diamond problem occurs, when the same class is inherited multiple times through different inheritance paths. This isn’t a problem for interfaces (and never was), as they only define a contract and specifying the same contract multiple times makes no difference.
The main problem is not associated with the methods but the data of that super type. Should the instance state of A exist once or twice in that case? If once, C and B can have different, conflicting constraints on A’s instance state. Both classes might also assume to have full control over A’s state, i.e. not consider that other class having the same access level. If having two different A states, a widening conversion of a D reference to an A reference becomes ambiguous, as either A could be meant.
Interfaces don’t have these problems, as they do not carry instance data at all. They also have (almost) no accessibility issues as their methods are always public. Allowing default methods, doesn’t change this, as default methods still don’t access instance variables but operate with the interface methods only.
Of course, there is the possibility that B and C declared default methods with identical signature, causing an ambiguity that has to be resolved in D. But this is even the case, when there is no A, i.e. no “diamond” at all. So this scenario is not a correct example of the “Diamond Problem”.
Methods introduced by interfaces may always be overriden, while methods introduced by classes could be final. This is one reason why you potentially couldn't apply the same strategy for classes as you could for interfaces.
The conflict described as "diamond problem" can best be illustrated using a polymorphic call to method A.m() where the runtime type of the receiver has type D: Imagine D inherits two different methods both claiming to play the role of A.m() (one of them could be the original method A.m(), at least one of them is an override). Now, dynamic dispatch cannot decide which of the conflicting methods to invoke.
Aside: the distinction betwee the "diamond problem" and regular name clashes is particularly relevant in languages like Eiffel, where the conflict could be locally resolved for the perspective of type D, e.g., by renaming one method. This would avoid the name clash for invocations with static type D, but not for invocations with static type A.
Now, with default methods in Java 8, JLS was amended with rules that detect any such conflicts, requiring D to resolve the conflict (many different cases exist, depending on whether or not some of the types involved are classes). I.e., the diamond problem is not "solved" in Java 8, it is just avoided by rejecting any programs that would produce it.
In theory, similar rules could have been defined in Java 1 to admit multiple inheritance for classes. It's just a decision that was made early on, that the designers of Java did not want to support multiple inheritance.
The choice to admit multiple (implementation) inheritance for default methods but not for class methods is a purely pragmatic choice, not necessitated by any theory.

Data access Objects and JPA

Apologies for the "pedantic" question, however I have been wondering how to structure the following. If I am building a JPA type application, my persistent classes (annotated with #Table etc) may be collected in a foo.bar.entities package. However, I may also have objects that are of a similar structure (POJO) that are not use for persistence. Where would I place these so that it was clear that there function was other than JPA; foo.bar.dto (for data transfer object) - or am I confusing my terminology? Maybe they are "model" classes - although that is really what the entities are?
Term 'dto' is mostly used to refer to these kind of objects. Use vertical slice architecture to place these classes under a different package.
Now, you can place dto's under dto package and entity/domain classes under domain package. You can also use entities as your package name, but just be consistent all across your project with your naming conventions.

Resources