Java reflection run-time performance - java

This is an academical exercise (disclaimer).
I'm building an application that will profit from being as fast as possible as it will compete with others.
I know that declaring a class using reflection (example below) will suffer a huge penalty as opposed to a standard declaration.
Class mDefinition = Class.forName("MySpecialClassString");
Constructor mConstructor = mDefinition.getConstructor(new Class[]{MySpecialClass.class});
myClass = (MySpecialClass) mConstructor.newInstance(this);
However, after declaring myClass if I use it in a standard fashion myClass.myMethod() will I also suffer from performance hogs or will it be the same as if I had declared the class in a standard fashion?

There will be a performance penalty when you first instantiate the object. Once the class is loaded, its the same as if it had been instantiated normally, and there will be no further performance penalty.
Going further, if you call methods using reflection, there will be a performance penalty for about fifteen times (default in Java), after which the reflected call will be rewritten by the JVM to be the exact same as a statically compiled call. Therefore, even repeatedly reflected method calls will not cause a performance decrease, once that bytecode has been recompiled by the JVM.
See these two link for more information on that:
Any way to further optimize Java reflective method invocation?
http://inferretuation.blogspot.com/2008/11/in-jit-we-trust.html

Once the class has been loaded you should be fine. The overhead is associated with inspecting the runtime structures that represent the class, etc. Calling methods in a standard fashion should be fine, however if you start searching for methods by name or signature, that will incur additional overhead.

Chris Thompson's answer is on the mark. However I'm confused by your code example.
this will dynamically load the class:
Class mDefinition = Class.forName("MySpecialClassString");
This will get a Contructor for your class, which takes an instance of that same class as an argument. Also note that you're accessing the class at compile time with MySpecialClass.class:
Constructor mConstructor = mDefinition.getConstructor(new Class[]{MySpecialClass.class});
This is instantiating a MySpecialClass by passing this into the constructor:
myClass = (MySpecialClass) mConstructor.newInstance(this);
Based on the constructor argument, does that mean we are in an instance method of MySpecialClass? Very confused.
EDIT: This is closer to what I would have expected to see:
Class<?> mDefinition = Class.forName("MySpecialClassString");
//constructor apparently takes this as argument
Class<?> constructorArgType = this.getClass(); //could be ThisClassName.class
Constructor<?> mConstructor = mDefinition.getConstructor(constructorArgType);
MySpecialInterface mySpecialInstance = (MySpecialInterface)mConstructor.newInstance(this);
where MySpecialInterface is an interface used to interact with your dynamically loaded classes:
interface MySpecialInterface {
//methods used to interface with dynamically loaded classes
}
Anyway please let me know if I'm misunderstanding or off base here.

Related

Dynamically creating a java class through one method's bytecode

I understand if I have a class file I can load it at run time and execute it's methods through classLoader. However, what if I only have bytecode or java code for a single method? Is it possible to dynamically create a class at run time and then invoke the method?
There is a planned feature, JEP 8158765: Isolated Methods, also on the bugtracking list, which would allow to load and execute such bytecode, without generating a fully materialized Class. It could look like
MethodHandle loadCode(String name, MethodType type, byte[] instructions, Object[] constants)
in the class MethodHandles.Lookup
However, this feature is in draft state, so it could take significant time before becoming an actual API and it might even happen that it gets dropped in favor of an entirely different feature covering the use cases the authors of the JEP have in mind.
Until then, there is no way around generating the necessary bytes before and after the method’s bytecode, to describe a complete class and loading that class. But of course, you can write your own method accepting a method’s byte code and some metadata, like the expected signature, generating such a class and reuse that method.
Note that there’s an alternative to creating a new ClassLoader, Class<?> defineClass​(byte[] bytes) in class MethodHandles.Lookup which allows to add a class to an existing class loading context, since Java 9.
The bytecode for a method refers to entries in the class's constant pool, so it doesn't make sense in isolation.

Is it mandatory utility class should be final and private constructor?

By making private constructor, we can avoid instantiating class from anywhere outside. and by making class final, no other class can extend it. Why is it necessary for Util class to have private constructor and final class ?
This is not a mandate from a functional point of view or java complication or runtime. However, it's a coding standard accepted by the wider community. Even most static code review tools, like checkstyle, check that such classes have this convention followed.
Why this convention is followed is already explained in other answers and even OP covered that, but I'd like to explain it a little further.
Mostly utility classes are a collection of methods/functions which are independent of an object instance. Those are kind of like aggregate functions as they depend only on parameters for return values and are not associated with class variables of the utility class. So, these functions/methods are mostly kept static. As a result, utility classes are, ideally, classes with only static methods. Therefore, any programmer calling these methods doesn't need to instantiate the class. However, some robo-coders (maybe with less experience or interest) will tend to create the object as they believe they need to before calling its method. To avoid that, we have 3 options:
Keep educating people to not instantiate it. (No sane person can keep doing it.)
Mark the utility class as abstract: Now robo-coders will not create the object. However, reviewers and the wider java community will argue that marking the class as abstract means you want someone to extend it. So, this is also not a good option.
Private constructor: Not protected because it'll allow a child class to instantiate the object.
Now, if someone wants to add a new method for some functionality to the utility class, they don't need to extend it: they can add a new method as each method is independent and has no chance of breaking other functionalities. So, no need to override it. Also, you are not going to instantiate it, so no need to subclass it. Better to mark it final.
In summary, instantiating a utility class (new MyUtilityClass()) does not make sense. Hence the constructors should be private. And you never want to override or extend it, so mark it final.
It's not necessary, but it is convenient. A utility class is just a namespace holder of related functions and is not meant to be instantiated or subclassed. So preventing instantiation and extension sends a correct message to the user of the class.
There is an important distinction between the Java Language, and the Java Runtime.
When the java class is compiled to bytecode, there is no concept of access restriction, public, package, protected, private are equivalent. It is always possible via reflection or bytecode manipulation to invoke the private constructor, so the jvm cannot rely on that ability.
final on the other hand, is something that persists through to the bytecode, and the guarantees it provides can be used by javac to generate more efficient bytecode, and by the jvm to generate more efficient machine instructions.
Most of the optimisations this enabled are no longer relevant, as the jvm now applies the same optimisations to all classes that are monomorphic at runtime—and these were always the most important.
By default this kind of class normally is used to aggregate functions who do different this, in that case we didn't need to create a new object

Java object instantiation - where

I am fairly new to Java, this particular question has arisen because I am trying to do some Swing programming for the first time but it is a general Java question.
I have a class with some instance variables, I need to create one (and only one) object to hold the variables and methods. Is there a best/approved place to create the object, should it be declared and instantiated in the class' attribute definition :
public class TestClass {
static TestClass tC = new TestClass();
...
or declared in the class' attributes definition and instantiated by a static method (e.g. main later on) :
public class TestClass {
static TestClass tC;
...
public static void main(String[] args) {
tc = new TestClass();
}
Or somewhere else, does it matter?
Or somewhere else, does it matter?
It certainly does matter, if you see it generally enough.
Placing the initialization inside the main method will be relevant only to those uses of your class where this particular main method is executed. If your class has any scope of usage larger than a single program, that particular avenue of initialization will be as good as non-existent.
Placing the initialization inline with declaration ensures that the field is initialized for all users of the class, independent of the code path taken to access it.
Additionally note that in real-world programs, hardcoding singleton initialization like that very often interferes with the full extent of intended usage. The singleton often depends on some kind of initialization data, and that data may not be available at class initialization time. There may be several independent "zones" in a larger program, each needing a differently initialized singleton. Testing concerns usually imply substituting a mock implementation instead of your class, and so on.
So, either of your approaches may work for you currently, but also neither of them may be enough in a more complex scenario.
If you instantiate the variable where you declare it as a field, it will be created as the class is first initialised (that is, when it's first "touched".) If you initialise it in the main method, then it will be initialised, well, whenever that particular line in that method is executed.
If it doesn't make a difference functionally, then one could argue that the inline declaration ensures that it's never null when a method comes to deference it (this could be further strengthened by making the field final if you can.) In the grand scheme of things though, it probably doesn't matter too much.

What is the main difference in object creation between Java and C++?

I'm preparing for an exam in Java and one of the questions which was on a previous exam was:"What is the main difference in object creation between Java and C++?"
I think I know the basics of object creation like for example how constructors are called and what initialization blocks do in Java and what happens when constructor of one class calls a method of another class which isn't constructed yet and so on, but I can't find anything obvious. The answer is supposed to be one or two sentences, so I don't think that description of whole object creation process in Java is what they had in mind.
Any ideas?
What is the main difference in object creation between Java and C++?
Unlike Java, in C++ objects can also be created on the stack.
For example in C++ you can write
Class obj; //object created on the stack
In Java you can write
Class obj; //obj is just a reference(not an object)
obj = new Class();// obj refers to the object
In addition to other excellent answers, one thing very important, and usually ignored/forgotten, or misunderstood (which explains why I detail the process below):
In Java, methods are virtual, even when called from the constructor (which could lead to bugs)
In C++, virtual methods are not virtual when called from the constructor (which could lead to misunderstanding)
What?
Let's imagine a Base class, with a virtual method foo().
Let's imagine a Derived class, inheriting from Base, who overrides the method foo()
The difference between C++ and Java is:
In Java, calling foo() from the Base class constructor will call Derived.foo()
In C++, calling foo() from the Base class constructor will call Base.foo()
Why?
The "bugs" for each languages are different:
In Java, calling any method in the constructor could lead to subtle bugs, as the overridden virtual method could try to access a variable which was declared/initialized in the Derived class.
Conceptually, the constructor’s job is to bring the object into existence (which is hardly an ordinary feat). Inside any constructor, the entire object might be only partially formed – you can know only that the base-class objects have been initialized, but you cannot know which classes are inherited from you. A dynamically-bound method call, however, reaches “forward” or “outward” into the inheritance hierarchy. It calls a method in a derived class. If you do this inside a constructor, you call a method that might manipulate members that haven’t been initialized yet – a sure recipe for disaster.
Bruce Eckel, http://www.codeguru.com/java/tij/tij0082.shtml
In C++, one must remember a virtual won't work as expected, as only the method of the current constructed class will be called. The reason is to avoid accessing data members or even methods that do not exist yet.
During base class construction, virtual functions never go down into derived classes. Instead, the object behaves as if it were of the base type. Informally speaking, during base class construction, virtual functions aren't.
Scott Meyers, http://www.artima.com/cppsource/nevercall.html
Besides heap/stack issues I'd say: C++ constructors have initialization lists while Java uses assignment. See http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6 for details.
I would answer: C++ allows creating an object everywhere: on the heap, stack, member. Java forces you allocate objects on the heap, always.
In Java, the Java Virtual Machine (JVM) that executes Java code has to might1 log all objects being created (or references to them to be exact) so that the memory allocated for them can later be freed automatically by garbage collection when objects are not referenced any more.
EDIT: I'm not sure whether this can be attributed to object creation in the strict sense but it surely happens somewhen between creation and assignment to a variable, even without an explicit assignment (when you create an object without assigning it, the JVM has to auto-release it some time after that as there are no more references).
In C++, only objects created on the stack are released automatically (when they get out of scope) unless you use some mechanism that handles this for you.
1: Depending on the JVM's implementation.
There is one main design difference between constructors in C++ and Java. Other differences follow from this design decision.
The main difference is that the JVM first initializes all members to zero, before starting to execute any constructor. In C++, member initialization is part of the constructor.
The result is that during execution of a base class constructor, in C++ the members of the derived class haven't been initialized yet! In Java, they have been zero-initialized.
Hence the rule, which is explained in paercebal's answer, that virtual calls called from a constructor cannot descend into a derived class. Otherwise uninitialized members could be accessed.
Assuming that c++ uses alloc() when the new call is made, then that might be what they are
looking for. (I do not know C++, so here I can be very wrong)
Java's memory model allocates a chunk of memory when it needs it, and for each new it uses of
this pre-allocated area. This means that a new in java is just setting a pointer to a
memory segment and moving the free pointer while a new in C++ (granted it uses malloc in the background)
will result in a system call.
This makes objects cheaper to create in Java than languages using malloc;
at least when there is no initialization ocuring.
In short - creating objects in Java is cheap - don't worry about it unless you create loads of them.

Are there inline functions in java?

Is there a concept of inline functions in java, or its replaced something else? If there is, how is it used? I've heard that public, static and final methods are the inline functions. Can we create our own inline function?
In Java, the optimizations are usually done at the JVM level. At runtime, the JVM perform some "complicated" analysis to determine which methods to inline. It can be aggressive in inlining, and the Hotspot JVM actually can inline non-final methods.
The java compilers almost never inline any method call (the JVM does all of that at runtime). They do inline compile time constants (e.g. final static primitive values). But not methods.
For more resources:
Article: The Java HotSpot Performance Engine: Method Inlining Example
Wiki: Inlining in OpenJDK, not fully populated but contains links to useful discussions.
No, there is no inline function in java. Yes, you can use a public static method anywhere in the code when placed in a public class. The java compiler may do inline expansion on a static or final method, but that is not guaranteed.
Typically such code optimizations are done by the compiler in combination with the JVM/JIT/HotSpot for code segments used very often. Also other optimization concepts like register declaration of parameters are not known in java.
Optimizations cannot be forced by declaration in java, but done by compiler and JIT. In many other languages these declarations are often only compiler hints (you can declare more register parameters than the processor has, the rest is ignored).
Declaring java methods static, final or private are also hints for the compiler. You should use it, but no garantees. Java performance is dynamic, not static. First call to a system is always slow because of class loading. Next calls are faster, but depending on memory and runtime the most common calls are optimized withinthe running system, so a server may become faster during runtime!
Java does not provide a way to manually suggest that a method should be inlined. As #notnoop says in the comments, the inlining is typically done by the JVM at execution time.
What you said above is correct. Sometimes final methods are created as inline, but there is no other way to explicitly create an inline function in java.
Well, there are methods could be called "inline" methods in java, but depending on the jvm. After compiling, if the method's machine code is less than 35 byte, it will be transferred to a inline method right away, if the method's machine code is less than 325 byte, it could be transferred into a inline method, depending on the jvm.
Real life example:
public class Control {
public static final long EXPIRED_ON = 1386082988202l;
public static final boolean isExpired() {
return (System.currentTimeMillis() > EXPIRED_ON);
}
}
Then in other classes, I can exit if the code has expired. If I reference the EXPIRED_ON variable from another class, the constant is inline to the byte code, making it very hard to track down all places in the code that checks the expiry date. However, if the other classes invoke the isExpired() method, the actual method is called, meaning a hacker could replace the isExpired method with another which always returns false.
I agree it would be very nice to force a compiler to inline the static final method to all classes which reference it. In that case, you need not even include the Control class, as it would not be needed at runtime.
From my research, this cannot be done. Perhaps some Obfuscator tools can do this, or, you could modify your build process to edit sources before compile.
As for proving if the method from the control class is placed inline to another class during compile, try running the other class without the Control class in the classpath.
so, it seems there arent, but you can use this workaround using guava or an equivalent Function class implementation, because that class is extremely simple, ex.:
assert false : new com.google.common.base.Function<Void,String>(){
#Override public String apply(Void input) {
//your complex code go here
return "weird message";
}}.apply(null);
yes, this is dead code just to exemplify how to create a complex code block (within {}) to do something so specific that shouldnt bother us on creating any method for it, AKA inline!
Java9 has an "Ahead of time" compiler that does several optimizations at compile-time, rather than runtime, which can be seen as inlining.

Categories

Resources