Why there is no use of pointer concept in java? [duplicate] - java

This question already has answers here:
Does java really have pointers or not? [closed]
(9 answers)
Closed 9 years ago.
As we know that in c/c++ pointer concept are present and pointer concept is a very good one.Then, Why the java developers remove it and if we can't use in java the what is it's pros and cons.

Pointers are forbidden in managed languages by default to allow memory management to be opaque - for example, you can have a compacting garbage collector that moves objects closer together to free up larger blocks of free space and improve cache coherency, if there are no pointers. But if there are pointers, then every pointer would either need to be updated or become valid every garbage collection, which is infeasible.
(This is just one reason of course :) but an example of how allowing pointers drastically changes what your programming language can do )
In some managed languages, like C#, you can declare unsafe {} blocks, where you can used unmanaged memory and pointers, but only there.

Related

JNI GetDirectBufferAddress vs. ByteBuffer.array() [duplicate]

This question already has answers here:
Gets byte array from a ByteBuffer in java
(6 answers)
Closed 6 years ago.
The community reviewed whether to reopen this question 6 months ago and left it closed:
Original close reason(s) were not resolved
I have to mix c++ code with java.
The java part allocates a java.nio.ByteBuffer and the c++ part gets it's address via env->GetDirectBufferAddress(buffer) as a jbyte* and fills in data.
ByteOrder is ok. Data can be retrieved in java via buffer.get() .getLong() etc.
However, the method buffer.array() fails and hasArray() returns false.
If I use buffer.allocate(size) instead of .allocateDirect(size) the method array() works well, but my c++ code gets a DirectBufferAddress of NULL and fails.
My question: how can I best combine both worlds, with least copying of data?
Or, how to easiest fill a java byte[] with native c++ data ?
ByteBuffer class is indeed confusing. It is actually a wrapper around one of two entirely different classes: DirectByteBuffer and ArrayByteBuffer. Why this happened, is a question for historians.
As far as the programmers are concerned, we must use DirectByteBuffer to achieve fastest, no-copy access from C, but access to DirectByteBuffer from Java may be quite slow, and it lacks the flexibility of byte[]. The array-based ByteBuffer has no advantage for C libraries, but it may be much more efficient on the Java side.
On the other hand, JNI does provide access to primitive arrays, including byte[]. In many cases, such access does not involve copy, especially if you use GetPrimitiveArrayCritical(). Well, there is no guarantee. But If you use a modern optimized JVM on modern hardware with abundant physical RAM and almost unlimited virtual RAM, your chances to have efficient access from both C/C++ and Java are very high.

Why Java doesn't allow object on stack? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am taking some classes and object lessons in Java having C++ background. I want to know the reason why we cannot choose the objects to be declared on the stack memory? Why must everything go on the heap except for the primitive types?
Here's something to clarify what I was asking.
Essentially, if we have:
Scanner input = new Scanner(System.in);
Then why cannot we have it on stack in the first place?
One of the strongest attractors of the original Java design (in mid-1990s) was simplicity. Supporting heap-based objects is essential, whereas stack-based ones are an optimization. Java is not alone here: many languages take that approach (LISP, Haskell, JavaScript, Ruby, etc.). Stack-based allocation does happen in Java, but only as an internal optimization trick and not something that the user can control.
Especially keep in mind that there is an essential difference in how a pointer to an object passed to a function ("a reference passed to a method" in Java-speak) can be treated by the callee: it is not allowed to retain the pointer if it's stack-based. This alone creates huge complications and bug opportunities.
Finally, stack-based objects bring much less to a garbage-collected language than to manually-managed languages like C and C++.
The data on the stack, say a C struct, disappears after the function call has returned. Hence one would need copying and correction of pointers.
Think of the hidden extra functionality needed here:
struct S* f() {
struct S s = ...;
g(&s);
return &s;
}
Java was meant as simplification, having its own management of memory, and doing things immediately on the heap seemed more direct, less convoluted.
This in view of C++, with its copy constructors, pointers and aliases.
Java does not allow explicit on stack allocation of objects. The language is not competing with low level languages such as C, and the creators of the language made this choice as a simplification.
However times change, and Java has grown since its humble beginnings. As the JVM becomes more sophisticated, automatic allocation of objects to the stack has become possible. The rationale for this is similar to the 'register' keyword in C; let the compiler manage the low level detail. It has become better at doing it than humans. In Java automatic allocation of objects onto the stack has been hampered by two factors, firstly the Sun/Oracle JVM is very old and very complex now. It is difficult to change, and Oracle has been careful about preventing backwards breaks. Secondly, so far their work on stack allocations has not yielded the large benefits that were expected. It did improve some situations, but the JVM has its own trade offs and behaviours. So this comes down to a question of time/pay-off and priorities. I believe that work to improve the benefits of automatic allocation continues behind the scenes; but there are no plans to make it explicit.
To put it simple, the key advantage of objects on stack is that the memory is automatically managed for you. When function puts objects on stack, they are cleaned from memory on function exit.
Since java already has automated garbage collection, this key advantage doesn't bring that much.
Sure there is a speed of access performance price that you might pay by being unable to allocate objects on stack directly, but as Marko mentioned, there are internal optimizations that might do just that.
Why must everything go on the heap except for the primitive types?
This statement is not accurate. Primitive types can go on the heap as well if they are part of a class instance. A local variable is stored on the stack, where as class variables are on the heap.
As for why objects are stored on the heap. It's after all a design decision. One reason is that it is a managed area in the JVM that is subject to garbage collection. As a managed area in the JVM, it may be organized in generations and may grow or shrink in size. See this section from the JVM specification:
The Java Virtual Machine has a heap that is shared among all Java Virtual Machine threads. The heap is the run-time data area from which memory for all class instances and arrays is allocated.
The heap is created on virtual machine start-up. Heap storage for objects is reclaimed by an automatic storage management system (known as a garbage collector); objects are never explicitly deallocated.

Does Java have pointers? if yes, how manipulate them? [duplicate]

This question already has answers here:
Does Java have pointers?
(12 answers)
Closed 9 years ago.
I am new to java and confused.
Does Java have pointers? if yes, how to manipulate them? how to perform operations like ptr++ etc?
Yes, java has pointers and they call them references.
But reference manipulation is not possible in java. That is, you can not do ref++ and things like that.
You can just allocate memory to an object and assign it to a reference, de-allocation too is done by garbage collector in JVM. So you are free of free.
Java doesn't have pointers, but you can make pointer manipulations with sun.misc.Unsafe: Java Magic. Part 4: sun.misc.Unsafe:
static Object shallowCopy(Object obj) {
long size = sizeOf(obj);
long start = toAddress(obj);
long address = getUnsafe().allocateMemory(size);
getUnsafe().copyMemory(start, address, size);
return fromAddress(address);
}
Though in my practice I have never wanted to do such things and they are considered a bad practice by community unless you're developing a super-fast library like Kryo.
You dont have pointers, or at least not how you are used to thed from C/C++/whatever. You have object references instead, but you cant ++ those.
The following examples are pointers set to reserved memory:
Object o = new Object();
int[] myInts = new int[32];
You can manipulate pointers like this:
Object myObject = otherObject;
...if both types match.
You cannot do pointer manipulation as you could in C, because these are usually dangerous operations. Java in general tries to reduce coding errors by disallowing dangerous operations as much as possible. In the beginning this feels restraining, but once you get to know Java and suddenly can write a whole page of code without a single bug, you understand why this is a core design of the language.

Java: Find out memory size of object? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
In Java, what is the best way to determine the size of an object?
In Actionscript I can usually just do:
var myVar:uint = 5;
getSize(myVar)
//outputs 4 bytes
How do I do this in Java?
If you turn off -XX:-UseTLAB you can check the Runtime.freeMemory() before and after. However in the case of local variables, they don't take space on the heap (as they use the stack) and you can't get it size.
However, an int is a 32-bit sign value and you can expect it will use 4-bytes (or more depending on the JVM and the stack alignment etc)
The sizeof in C++ is useful for pointer arithmetic. Since Java doesn't allow this, its isn't useful and possibly deliberately hidden to avoid developers worrying about low level details.
The only reason C had a sizeOf intrinsic (function? well something) was because they needed it for manual memory management and some pointer arithmetic stuff.
There's no need to have that in Java. Also how much memory an object takes up is completely implementation defined and can't be answered reliably, but you can try some statistics by allocating lots of the same object and averaging - this can work nicely if you observe some basic principles, but that's boring.
If we know some basics about our VM we can also just count memory, so for Hotspot:
2 words overhead per object
every object is 8byte aligned (i.e. you have to round up to the next multiple of 8)
at least 1 word for variables, i.e. even if you have an object without any variables we "waste" 1 word
Also you should know your language spec a bit, so that you understand why an inner class has 1 additional reference than is obvious and why a static inner class does not.
A bit of work, but then it's generally a rather useless thing to know - if you're that worried about memory, you shouldn't be using neither ActionScript nor Java but C/C++ - you may get identical performance in Java, but you'll generally use about a factor of 2 more memory while doing so...
I believe there is no direct way of doing this. #Peter Lawrey 's suggestion could be a close approximation. But, you cannot rely on calculating the object size by taking the difference between the available free memory before and after the Object buildup, as there could be lots of other allocations in background happening from other threads as well. Also, there could be a possibility that the garbage collector could fire up and free up some memory in between your opertions. Also specially, in a multithreaded environment relying in the memory difference is definitely not a solution.

How big is an Object? Why is there no sizeof? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
In Java, what is the best way to determine the size of an object?
sizeof java object
C has a sizeof operator, and it needs to have one, because the user has to manage calls to malloc, and because the size of primitive types (like long) is not standardized.
But in java cant we find the sizeof an object?
Also why java doesnot have sizeof operator or method?
You've kind of answered your own question, in c you manage memory in java the jvm does.
In c you're directly allocating the memory for the data structures you're storing (malloc) and so you often need to know the sizes of these things.
In java the memory system is largely abstracted away so you don't (usually) care you just call new and it'll do whatever it does and if different jvms do things differently the memory used by the classes you've declared may vary.
Sometimes it is useful to know how much memory your classes are taking up (say you're trying to reduce your memory footprint in a tightly constrained environment) but it's pretty rare that you'd need that sort of information at runtime.
Also why java doesnot have sizeof operator or method?
Answer #1 - because Java doesn't need this. In C, the sizeof operator is needed so that you can malloc objects of the right size, for doing certain kinds of pointer arithmetic, and so on. In Java, you don't need to (and can't) do those kinds of thing.
Answer #2 - the size of an object in Java is rather rubbery, and indeed can change through the lifetime of the object (at least, in some JVMs). Ergo, a sizeof operator would be problematic.
In c there is a lot of work with pointers. Programmer should manage memory by himself, so he should know the size of types. But in Java there is no manual memory management. JVM does all it, so no need in sizeof.
In C you have to manually manage memory usage, you stated as much in your question. Since you need to allocated space for an object and remove it, the sizeof operator is required to do this quickly and easily. In Java, memory management is taken care of by the JVM. You don't need to manually allocate and de-allocate memory so the sizeof operator isn't necessary.

Categories