Why class objects only created dynamically in java? - java

This question already asked before but I don't find good understandable answer from there.
I would actually want to know that unlike c++ class objects can't be created statically in java why ? and what are the main disadvantages to create objects statically that java designers want to prevent to be occur ?
Thanks.

Good question. One is tempted to say that it is because the
authors of the language knew better than you what value types
you need, and provided them, and didn't want to let you define
new ones (e.g. like Complex). And there's certainly some of
that: it also explains the lack of operator overloading.
But I suspect that that wasn't the reason in the minds of the
Java authors. You need dynamic allocation and pointers (what
Java calls references) in some cases, such as when polymorphism
is involved, and the Java authors simply decided that they would
only support this idiom, rather than making the language more
complex by having it support several different idioms. It's
a pain, of course, when you actually need value semantics, but
with care, you can simulate them (java.lang.String would be
a good example) by making the class final and immutable, with
"operators" which return a new instance.
Of course, the added expressiveness of C++ does give more
possibility for errors: it's easy to take the address of a local
variable, for example, and end up with a dangling pointer. But
just because you can do something doesn't mean that you have to;
in C++, an incompetent programmer can make the program crash
immediately, where as in Java, he'll generally end up with
a wrong result (although uncaught exceptions aren't that rare
either).

Edit: It appears the poster may actually be asking why can't Objects be static in Java?, in which case, the answer is "they can" and I have added that to the answer at the bottom. If however the question is why can't Objects be allocated on the stack as they can in C++ then the first part of this answer attempts to deal with that:
I guess it boils down to the design goals of the Java language.
Because java has a garbage collector it doesn't really need to have stack allocated objects.
Trying to make things simpler, safer, familiar, while keeping them fast and consistent were design goals of the Java language designers.
Quoting from here http://www.oracle.com/technetwork/java/simple-142339.html (emphasis is mine):
Simplicity is one of Java's overriding design goals. Simplicity and
removal of many "features" of dubious worth from its C and C++
ancestors keep Java relatively small and reduce the programmer's
burden in producing reliable applications. To this end, Java design
team examined many aspects of the "modern" C and C++ languages to
determine features that could be eliminated in the context of modern
object-oriented programming.
One of those features that the designers decided was of "dubious worth" (or unnecessarily complicated the language or its Garbage Collection processes) were stack-allocated Objects.
These online chapters cover the design goals of the Java language in-depth.
Reviewing the comments I believe that I may have misinterpretted the original poster's question because the question seems to be confusing the two completely orthogonal concepts of allocating Objects on the stack with statically allocated Objects.
Stack allocation refers to value Objects that exist only within their current scope and occupy space on the stack.
Static allocation refers to instances that exist per Class - Objects that can exist for the lifetime of the application and are initialized within a static allocation block.
Java doesn't support the former concept (except with primitive data types) for the reasons explained above; but it certainly does support the latter. It is perfectly acceptable Java code to instantiate a static Object belonging to a class. A very simple example of a static Class Object would be this snippet of code:
public class Foo {
public static Integer integerValue = new Integer(32);
}
This would create a single public instance of an Integer Object that belongs to the class Foo. Because it is public in this example, one could access it and set it by calling:
Foo.integerValue = 57;
Note that only one (effectively global) copy exists of the integerValue regardless of how many Foo instances are instantiated.
A common use of statics is for class constants (declared with the the final modifier), but static variables in Java do not have to be constant: they are mutable by default if you omit the final modifier. Static variables need to be used with caution in multi-threaded applications, but that's another story.
For more information on static variables in java, you can read about them here:
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
and here:
http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
Hopefully the helps.

Related

Can Java lambda expressions be guaranteed not to hold a reference to `this`?

If a lambda expression does not refer to any methods or fields of the surrounding instance, does the language guarantee that it doesn't hold a reference to this?
In particular, I want to use lambda expressions to implement java.lang.ref.Cleaner actions. For example:
import static some.Global.cleaner;
public class HoldsSomeResource {
private final Resource res;
private final Cleanable cleanup;
public HoldsSomeResource(Resource res) {
this.res = res;
cleanup = cleaner.register(this, () -> res.discard());
}
public void discard() {
cleanup.clean();
}
}
Clearly, it would be bad if the lambda expression implementing the cleanup action were to hold a reference to this, since it would then never become unreachable. It seems to work when I test it right now, but I can't find the obvious reference in the JLS that it is guaranteed to be safe, so I'm slightly worried that I might run into problems in alternative and/or future Java implementations.
The specification does indeed not mention this behavior, but there is a statement in this document from Brian Goetz:
References to this — including implicit references through unqualified field references or method invocations — are, essentially, references to a final local variable. Lambda bodies that contain such references capture the appropriate instance of this. In other cases, no reference to this is retained by the object.
While this isn’t the official specification, Brian Goetz is the most authoritative person we can have to make such a statement.
This behavior of lambda expressions is as intentional as it can be. The cited text continues with
This has a beneficial implication for memory management: while inner class instances always hold a strong reference to their enclosing instance, lambdas that do not capture members from the enclosing instance do not hold a reference to it. This characteristic of inner class instances can often be a source of memory leaks.
Note that this other behavior, inner class instances always holding an implicit reference to the outer this instance, also does not appear anywhere in the specification. So when even this behavior, causing more harm than good if ever being intentional, is taken for granted despite not appearing in the specification, we can be sure that the intentionally implemented behavior to overcome this issue will never be changed.
But if you’re still not convinced, you may follow the pattern shown in this answer or that answer of delegating to a static method to perform the Cleaner registration. This has the benefit of also preventing accidental use of members while still being simpler than the documentation’s suggested use of a nested static class.
I think you're safe. It's not an aspect of the JIT or a garbage collector implementation (stuff from "java.exe") ; this is done directly by the compiler ("javac.exe"). It's not going to 'backslide' and inject useless and potentially pricey variables. It also means you are not dependent on a JVM's behaviour: you're merely dependent on a compiler's behaviour. For starters, there aren't all that many (ecj and javac that's pretty much it - all others you might be thinking of are forks of those, or are wrappers around those), and I'm pretty sure both ecj and javac don't capture the this now and presumably never will in the future.
A bigger issue is that javac certainly won't complain if you 'accidentally' do happen to capture anything that requires the this ref; that will lead to the this ref getting silently captured and ruining your cleanup library rather thoroughly. It feels like you've designed a library here where it's rather all too easy to shoot yourself in the foot.
I'm not quite sure what you can do to fix this. Possibly you can lean into it and use ASM or bytebuddy or similar to tear the class open1 and doublecheck that the this ref is not seeing capture. It's probably not worth the potentially sizable time it'd take to chase down all the refs to ensure that this isn't captured in a roundabout fashion (where the lambda captures variable y, and y has a field of type Bar pointing at some instance and that instance has a field whose value is a ref back to the original this, thus, preventing collection), but checking for direct capture is potentially interesting. Possibly even only in an assert statement so any testcase that does it will result in an AssertionError thrown, failing the test, letting you know this error was made.
[1] You can get the bytes of any class with String.class.getResourceAsStream("String.class") - you can read that InputStream and feed it into ASM / bytebuddy / etc. The costs of running a class through such a loop are considerable, of course.

Any intention of overhauling existing Java platform classes (JEP 360)?

Brian Goetz mentioned in a recent article on InfoQ that making String final caused problems:
A good example where we pay for this tension is String; it is critical to the security of the platform that strings be immutable, and therefore String cannot be publicly extensible -- but it would be quite convenient for the implementation to have multiple subtypes. (The cost of working around this is substantial; Compact strings delivered significant footprint and performance improvements by giving special treatment to strings consisting exclusively of Latin-1 characters, but it would have been far easier and cheaper to do this if String were a sealed class instead of a final one.)
He also mentions that making a final class sealed is backward-compatible:
It is a binary- and source-compatible change to make an existing final class sealed. It is neither binary- nor source-compatible to seal a non-final class for which you do not already control all the implementations.
Is there any intention to go back to some of these final classes in the Java platform and make them sealed instead to gain performance benefits (i.e., making String sealed instead of final, with a few performant implementations)?
You're asking to predict the future, but also it sounds a bit like you expect there to be a lot of classes that would benefit from performance tuning. In addition it's not that sealing is required for improvement if improvement is warranted, it's just that it might have made things easier with String for example. Making String sealed now isn't as useful as it would've been if it had been sealed let's say 10 years ago.
String has always been a very special and important case, and because of that it has been extensively tuned (and de-tuned) even without sealed classes: interning, shared char array, compressed and compact strings. There has always been a very good incentive to do this, as it's very clear from any memory dump that String (or rather its internal char[], which in later versions is a byte[]) is what takes most memory in applications.
Do you think there's a final class that should really be tuned, or are you just assuming that the classes are not performant? Or are you hoping for some sort of general cleanup of the codebase, which would probably result in a very low ROI considering you'd need to make the changes for most likely very little performance improvement, but you would need to do a lot of testing.
In addition, other important non-String classes have been tuned in various ways as well, you've got Integer cache, JVM intrinsics and many other things, so sealing is not primarily (or even secondarily) a performance tool.

Why there is no local static variable in Java?

In C/C++ we use static local variables for maintaining a method's state. But why it is not supported in Java?
Yes, I can use an static field for this purpose. But isn't it a bit weird to create a field for maintaining only one method's state?
You have found the only solution.
Java dropped a number of complexities from C++, and this was one of them.
Static variables scoped to a function do nasty things to you in concurrency (e.g. strtok is a famously nasty one to use with pthreads, for exactly this reason).
In general, what you want is an object with state. The function in question should then have an object-level variable. Then you can create instances that each maintain state.
Much easier to understand/maintain/etc.
If you truly need to maintain state as a singleton, then static fields are it.
The Java language spec doesn't seem to defend the omission of variables that correspond to C static variables.
Hiding state in class methods has a few drawbacks when seen from a Java perspective. Generally the existence of a function-level static variable isn't the sort of implementation detail that you'd want to expose outside of that function.
But the method's state is actually part of the class's state, and method-level static variables would have to be serialized / deserialized any time the object is persisted. This might not sound common, coming from a C background, so I'll note a few common examples.
Application server clusters can pass user session objects between nodes in order to provide fault tolerance.
JAXB could be used to marshall an object into an XML document
JPA can be used to persist object state to a database
If the variable's value is worth saving when the object is persisted, then there's a good chance that code outside of that class will need to reference that value. And suddenly that means defining access levels -- is a static variable in a public method automatically public? Or would a programmer have to declare it so?
We also have to think about extensibility. Would derived classes be required to implement the same static variable? Or would there be a reference to the variable from the function in the base class?
It's more likely that the C method that would use a static local variable would be a good candidate for a class in Java. It has state and hopefully exists for a single purpose. There's little drawback to encapsulating the functionality into an object, and it makes for a cleaner separation between transient values (such as local variables) and more long-term state.
Some of the other answers show why you might not want to have this. But you can also ask why from a historical perspective.
To answer this you have to start to see why C does have static local variables. C has much fewer means than Java and C++ to limit the scope of a variable, the only options for static data are 'inside the file' and 'everywhere'. So this provides an extra layer, to limit the scope.
An important aspect of C++ is compatibility with, so it is allowed in C++ as well. But it doesn't need local static scope as much anymore, because there are many other means to limit scope of static data. The use is not popular in (modern) C++.
Java merely takes a lot of inspiration from C/C++, it didn't have to worry about backwards compatibility, so it could be left out.
Perhaps because methods are not objects in Java; so maintaining their state as you said make not much sense and I guess you'd have to create a new concept in the byte code for that; use an object as Tony K. said.
instance methods are invoked by the instance(objects) of the class . Static things belongs to the class not to the object that's why local variables are not static.Instance variables are static and they can also initialized at the time of class loading by static blocks.
enter image description here
for more information please visit :- https://www.youtube.com/watch?v=GGay1K5-Kcs&t=119s

Would an immutable keyword in Java be a good idea?

Generally speaking, the more I use immutable objects in Java the more I'm thinking they're a great idea. They've got lots of advantages from automatically being thread-safe to not needing to worry about cloning or copy constructors.
This has got me thinking, would an "immutable" keyword go amiss? Obviously there's the disadvantages with adding another reserved word to the language, and I doubt it will actually happen primarily for the above reason - but ignoring that I can't really see many disadvantages.
At present great care has to be taken to make sure objects are immutable, and even then a dodgy javadoc comment claiming a component object is immutable when it's in fact not can wreck the whole thing. There's also the argument that even basic objects like string aren't truly immutable because they're easily vunerable to reflection attacks.
If we had an immutable keyword the compiler could surely recursively check and give an iron clad guarantee that all instances of a class were immutable, something that can't presently be done. Especially with concurrency becoming more and more used, I personally think it'd be good to add a keyword to this effect. But are there any disadvantages or implementation details I'm missing that makes this a bad idea?
In general, immutable objects should be preferred over stateful objects, and it's currently fairly difficult to make an immutable object in Java. In fact, most OO languages have poor support for immutable objects, while most functional languages take them for granted, such as F#, Haskell, and Clojure.
Adding an immutable keyword to Java could make code...
Easier to write. No messing with final and private, no accidentally adding a method that makes the class mutable, and possibly no manually marking the class final (subclasses can add mutable state).
Easier to read. You don't need to say that the class is immutable in English, you can say it in the code itself. An immutable keyword is a good step toward self-documenting code.
Faster (theoretically). The more the compiler knows about your code, the more optimizations it can make. Without this keyword, every call to new ImmutableFoo(1, 2, 3) must create a new object, unless the compiler can prove that your class can't be mutated. If ImmutableFoo was marked with the immutable keyword, every such call could return the same object. I'm pretty sure new must always create a new object, which makes this point invalid, but effective communication with the compiler is still a good thing.
Scala's case classes are similar to an immutable keyword. An immutable keyword was also being considered in C# 5.
While making all fields final and also verifying any class references are also immutable is possible there are other situations where this becomes impossible.
What if your final class also includes some lazy loaded fields ?
One would need further support for marking such fields as immutable and lazy.
Taking a look at java.lang.String with its array of chars[] how could the compiler really know for sure that it is immutable ? Everybody knows string is but another similar class could very easily include a method which updates an array. Further support would need to verify that once the field was set, no other instruction could "write" to the array. Before long this becomes a very complex problem.
In the end any such keyword if it did work might help, but it still does not mean programs are any better. Good design by good coders means better results. Dumb coders can still write crap even if the platform limits some pitfalls.
I'm a big fan of immutability, so in my opinion, absolutely. The advantages of immutability in OO programming are innumerable, and it shouldn't be the domain of just functional programming languages.
IMHO, object-oriented frameworks (Java, .net, etc.) should include more array types: mutable array, immutable array, mutable array references, immutable array references, and read-only array references (a read-only reference could point to either a mutable or immutable array, but in neither case would allow writing). Without an immutable array type, it's hard to construct many efficient types in a way that can be proven to be immutable.

Glorified classes in the Java language

Some classes in the standard Java API are treated slightly different from other classes. I'm talking about those classes that couldn't be implemented without special support from the compiler and/or JVM.
The ones I come up with right away are:
Object (obviously) as it, among other things doesn't have a super class.
String as the language has special support for the + operator.
Thread since it has this magical start() method despite the fact that there is no bytecode instruction that "forks" the execution.
I suppose all classes like these are in one way or another mentioned in the JLS. Correct me if I'm wrong.
Anyway, what other such classes exist? Is there any complete list of "glorified classes" in the Java language?
There are a lot of different answers, so I thought it would be useful to collect them all (and add some):
Classes
AutoBoxing classes - the compiler only allows for specific classes
Class - has its own literals (int.class for instance). I would also add its generic typing without creating new instances.
String - with it's overloaded +-operator and the support of literals
Enum - the only class that can be used in a switch statement (soon a privilege to be given to String as well). It does other things as well (automatic static method creation, serialization handling, etc.), but those could theoretically be accomplished with code - it is just a lot of boilerplate, and some of the constraints could not be enforced in subclasses (e.g. the special subclassing rules) but what you could never accomplish without the priviledged status of an enum is include it in a switch statement.
Object - the root of all objects (and I would add its clone and finalize methods are not something you could implement)
References: WeakReference, SoftReference, PhantomReference
Thread - the language doesn't give you a specific instruction to start a thread, rather it magically applies it to the start() method.
Throwable - the root of all classes that can work with throw, throws and catch, as well as the compiler understanding of Exception vs. RuntimeException and Error.
NullPointerException and other exceptions such as ArrayIndexOutOfBounds which can be thrown by other bytecode instructions than athrow.
Interfaces
Iterable - the only interface that can be used in an enhanced for loop
Honorable mentions goes to:
java.lang.reflect.Array - creating a new array as defined by a Class object would not be possible.
Annotations They are a special language feature that behaves like an interface at runtime. You certainly couldn't define another Annotation interface, just like you can't define a replacement for Object. However, you could implement all of their functionality and just have another way to retrieve them (and a whole bunch of boilerplate) rather than reflection. In fact, there were many XML based and javadoc tag based implementations before annotations were introduced.
ClassLoader - it certainly has a privileged relationship with the JVM as there is no language way to load a class, although there is a bytecode way, so it is like Array in that way. It also has the special privilege of being called back by the JVM, although that is an implementation detail.
Serializable - you could implement the functionality via reflection, but it has its own privileged keyword and you would spend a lot of time getting intimate with the SecurityManager in some scenarios.
Note: I left out of the list things that provide JNI (such as IO) because you could always implement your own JNI call if you were so inclined. However, native calls that interact with the JVM in privileged ways are different.
Arrays are debatable - they inherit Object, have an understood hierarchy (Object[] is a supertype of String[]), but they are a language feature, not a defined class on its own.
Class, of course. It has its own literals (a distinction it shares with String, BTW) and is the starting point of all that reflection magic.
sun.misc.unsafe is the mother of all dirty, spirit-of-the-language-breaking hacks.
Enum. You're not allowed to subclass it, but the compiler can.
Many things under java.util.concurrent can be implemented without JVM support, but they would be a lot less efficient.
All of the Number classes have a little bit of magic in the form of Autoboxing.
Since the important classes were mentioned, I'll mention some interfaces:
The Iterable interface (since 1.5) - it allows an object to participate in a foreach loop:
Iterable<Foo> iterable = ...;
for (Foo foo : iterable) {
}
The Serializable interface has a very special meaning, different from a standard interface. You can define methods that will be taken into account even though they are not defined in the interface (like readResolve()). The transient keyword is the language element that affects the behaviour of Serializable implementors.
Throwable, RuntimeException, Error
AssertionError
References WeakReference, SoftReference, PhantomReference
Enum
Annotation
Java array as in int[].class
java.lang.ClassLoader, though the actual dirty work is done by some unmentioned subclass (see 12.2.1 The Loading Process).
Not sure about this. But I cannot think of a way to manually implement IO objects.
There is some magic in the System class.
System.arraycopy is a hook into native code
public static native void arraycopy(Object array1, int start1,
Object array2, int start2, int length);
but...
/**
* Private version of the arraycopy method used by the jit
* for reference arraycopies
*/
private static void arraycopy(Object[] A1, int offset1,
Object[] A2, int offset2, int length) {
...
}
Well since the special handling of assert has been mentioned. Here are some more Exception types which have special treatment by the jvm:
NullPointerException
ArithmeticException.
StackOverflowException
All kinds of OutOfMemoryErrors
...
The exceptions are not special, but the jvm uses them in special cases, so you can't implement them yourself without writing your own jvm. I'm sure that there are more special exceptions around.
Most of those classes isn't really implemented with 'special' help from the compiler or JVM. Object does register some natives which poke around the internal JVM structures, but you can do that for your own classes as well. (I admit this is subject to semantics, "calls a native defined in the JVM" can be considered as special JVM support.)
What /is/ special is the behaviour of the 'new', and 'throw' instructions in how they initialise these internal structures.
Annotations and numbers are pretty much all-out freaky though.

Categories

Resources