java pass by value and memory and cpu utilization - java

Coming from a C background I have a very basic question: Does pass by value of a larger datatype like a String array invoke something like a copy constructor in java.
So would this code result in creating duplicate list in memory by copying list in list2.
Thus double memory and cpu utilization.
String[] getList() {
String[] list = new String...
...
return list;
}
String [] list2 = getList();
Is my assumption correct? If yes, is there an alternative like passing pointers in C.
PS: if we let garbage collector do the job of cleaning extra memory wont this be another set of cpu utilization of cycles of cleaning the memory which shouldn't have been created at first place.

No, it won't double memory and CPU usage. In Java, all non-primitive types are stored as references and those references are passed by value.
So in your example, the getList method will construct an array on the heap and return a reference to that array. No array copy involved; just a reference copy.

No, the contents of the array will not be copied. A reference pointing to the array on the heap will be passed instead.
Java does not have pointers, it has references. In Java, references pointing to objects on the heap are passed as arguments and returned by methods. Arrays are objects in Java, so they are treated this way too.

Related

Java: Are generic ArrayLists faster than LinkedLists for iteration?

For an ArrayList of a particular type, we can find the size of object (of a particular type) in the ArrayList, and directly access the object at any index in O(1). This is because object references are stored in contiguous chunk of memory in ArrayList, and hence by skipping object_size * index memory locations, we access the memory location where the reference of desired object is residing.
Whereas, in LinkedList, we would have to iterate through each object till we reach the desired object.
For a generic ArrayList, containing different types of objects (with varying sizes), is get(index i) done in O(1)? If so, how?
You working under a misconception. Objects are not stored in arrays, only references (i.e. pointers) to objects are stored in the array. Objects themselves are on the heap. Therefore finding a specific object in an ArrayList by index will always be O(1) regardless of what it contains, and a LinkedList will be O(n).
Not directly an answer to your question, but it might be useful to consider the Apache commons-collection: FastArrayList
Giving it an initial capacity:
List<Integer> listOfLength = new FastArrayList(256);
for (String block : arrayOfBlocks) {
listOfLength.add(block.length());
}

Strings - Stack and heap in java

I know that Strings are stored on the heap and the reference to them is stored on the stack. So in the code below one would point to "John" on the heap from the stack and likewise two would point to "Smith" on the heap from the stack.
So what happens when i do one = two?
Does one now point to where two points to because two contains a reference to a point on the heap or does it change the "John" on the heap to "Smith"?
String one;
one = "John";
String two = "Smith"
one = two;
In your example, one now points to the same place as two. The original string on the heap "John" becomes garbage and is subject to garbage collection.
It's not possible to see in this example because String is immutable, but if these were mutable data structures such as an ArrayList, then modifying the object through one would make the same change visible through two, because they point to the same object.
Now one will point to the two .Since all string are immutable then when they are created then they are stored in heap and referenced by variable but when you make or assign new variable to same string then it will not explicitly create new string but just reference to same string which is in heap
from above picture you can easily understand the concept of immutability.
for reference Where does java reference variable stored?

Can array of int pointers in C++ be done as ArrayList of Integer references in Java?

I have an array int[] A = new int[100000] in Java and I want to create millions of subarrays of A. In C++ I would use arrays of pointers. Can I create ArrayList<Integer> subA and store references to elements of A such that I will not consume too much memory.
Right at the moment, I do create int[] subA = new int[some value less than A.length] objects which is very expensive and goes out of memory.
List.subList() does that : it creates a view over the original list. You would probably save memory by using that, since a sublist has only these 4 fields:
reference to the outer list
offset
size
modCount
Each sublist would thus consume something like 20 bytes.
Java has no concept of pointers, therefore you cannot use a list of Integers to refer to other objects, but what you can do is this:
List<List<Integer>> l = new ArrayList<List<Integer>>();
l.add(new ArrayList<Integer>()) // add a list which will hold integers as a reference in your main list.
If you're running out of memory, you need to allocate more heap memory to the JVM. Read up on the -Xmx startup parameters you can pass to the JVM.

Deleting An Entire Array

I have written a program for sorting an integer type array which involves the creation another array of the same size. After sorting, there is no use of the new array, so I want to completely get rid of it. So far, I've only found questions relating to the deletion of specific types of elements. Some help?
Information (if needed):
Original Array: A[n]
New Array: B[n]
B[n] has to be completely deleted.
The temp array will be "deleted" (or more correctly, the occupied memory will be eligible for garbage collection) automatically whenever you leave the method performing the sorting (assuming of course that the temp array is created inside the method).
There is almost never any need for explicit memory deallocation in Java.
Array is a reference type in Java. You can make an array reference null if you no longer wish to use it:
arr = null;
Set B to null.
B = null;
This way the garbage collector will clean it up whenever it runs. While you can't control when garbage collection happens since each JVM might have it's own garbage collection algorithm, you may suggest to the system that it should run the garbage collector to free up some memory.
You can do this by using
System.gc();
Note: As mentioned above, System.gc(); will only suggest that garbage collection be carried out but does not assure it.
Normally the gc() frees the memory which has no references. But you can also free the memory with array = null.
If the array is locally defined in your sorting method then it will be scheduled for garbage collection when your method ends as there will be no existing reference to it.
If it is a class or instance variable then set all references to it to null.
In Java you dont have to worry about memory deallocation. There is no such stuff like C's stdlib free(void*) or C++'s delete[] operator. Thee is only the garbage collector.
set B to an empty array
B = [];

Java ArrayList Memory Issue

I have the following code:
result = binding.downloadData(sourceURLString.replace("{CAT_ID}", catId), Data.class);
ArrayList<Data> mAllProducts = result.getProducts();
cloneList(mAllProducts);
System.gc();
And here is the deep copy of the mAllProducts ArrayList
static List<Data> clone;
public static void cloneList(ArrayList<Data> list) {
clone = new ArrayList<Data>();
for(Data item: list){
clone.add(new Data(item));
}
}
Data Constructor:
public Data(Data item2) {
this.imageUrl = item2.imageUrl;
*
*
}
My questions are:
Will the mAllProducts arraylist collected by the garbage collector?
Is the clone list a passed by value ArrayList?
If the answer at the 2nd question is yes, that means that the clone arraylist doesn't have a reference to the memory?
And finally, if the answer at the second question is yes, that means that will stay at the memory only for the time is being used by the system and then will be garbage collected?
1) No way to know, your gc call is merely a suggestion that the JVM try to perform a collection.
2) Everything in Java is pass by value.
3) I don't know what you mean. But your clone, assuming it creates new items for the list, and the items don't share references to any objects, is completely separate from the original list. Primitive values like ints are immutable, it's only object instances you have to worry about. It seems you are using a copy constructor, so be extra careful you copy any objects each item contains, as well as any items those children might contain; your copy needs to be deep.
4) I don't know what you mean. If you don't have any references to the original it will be eligible for collection the next time the GC runs.
Will the mAllProducts arraylist collected by the garbage collector?
Only when 1) The garbage collector decides to do so and 2) When it falls out of scope
Is the clone list a passed by value ArrayList?
Yes
If the answer at the 2nd question is yes, that means that the clone arraylist doesn't have a reference to the memory?
Definitely needs a reference to some point in memory, else it can't exist in a logical system i.e. a computer.
And finally, if the answer at the second question is yes, that means that will stay at the memory only for the time is being used by the system and then will be garbage collected?
Again the garbage collector will collect it when it is deemed fit to do so.

Categories

Resources