Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Thinking about this question, I don't think it would be bad since object references only take up 4 bytes of memory (in a 32-bit JVM), but intuitively I feel like I'm doing something wrong when I have many (+100) references to the same object. This usually happens when I create a certain class +100 times and each need to hold the reference.
I know I can re-design my code in most cases to avoid this, but sometimes its much easier to just keep the reference within each object.
Anyway, is it bad to have many references to the same object?
Having many references to the same object is unavoidable, but has no dissadvantage IMHO.
Every Class has a reference to it from every instance of that class. Each class loader has a reference from every class. The empty String is often the most referenced object with tens of thousands of references being common.
I know I can re-design my code in most cases to avoid this, but sometimes its much easier to just keep the reference within each object.
I suggest you do what you believe is simplest and clearest and this will be easiest to maintain.
Thinking about this question, I don't think it would be bad since object references only take up 4 bytes of memory (in a 32-bit JVM), but intuitively I feel like I'm doing something wrong when I have many (+100) references to the same object.
From a performance/resource utilization standpoint, references are waaaaaaaaaaaaaaaay more efficient than creating and destroying objects. Lots of ittybitty objects can fragment the heap and tax the memory manager/garbage collector. This is why it's usually worth the effort to make immutable objects singletons. Construction of even small objects in Java is more expensive than using references.
Most programs won't notice any significant difference, but some will.
This usually happens when I create a certain class +100 times and each need to hold the reference.
If every instance of a class references that object, use a static rather than instance variable to store the reference. You can use a static initializer to allocate it, or create a factory method to instantiate objects of the class and have the factory method allocate the referenced object the first time it is invoked.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Would it be overhead to always return a copy of collection/object field?
Clearly, yes it would be a overhead ... compared with returning a reference or a shallow copy.
But that's not really the point. The real point is whether the overhead is warranted / necessary, and whether it can be avoided by using some other data structure / design / technique. The answer to those questions depends on the context.
Here are some illustrations:
If a target object getter returns an immutable object, a copy is unnecessary. Example, any getter that returns a String.
If a target object getter returns an object that is not part of the target object abstraction, a copy is undesirable. Example list.get(int), Iterator.next().
If a target object getter returns a mutable object (or array) AND the returned object is part of the object's internal state AND the target doesn't necessarily trust the caller, then the getter should either copy it or wrap it ... or there may be a security problem.
The same may apply in non-security-related contexts; e.g. ArrayList.toArray(...) copies the list into an separate array rather than returning the list's backing array. (Similar for getChars() for a String, StringBuffer, etc.) This is all about maintaining the abstraction boundary so that on class won't "break" another one.
If a target object getter returns a mutable object (or array) AND the returned object is part of the object's internal state BUT the target object's API / abstraction boundary is designed to be "porous" (e.g. for performance reasons), then copying may be self defeating.
Of these, 3 is the only case where cloning is strictly mandatory. In 2, 4 and 5 you could argue that it is a matter of how you design the public (or internal) APIs for the classes, libraries, applications. And often there are many viable choices.
It is overhead for sure but there are already some framework classes which do that. It is also described in the book Effective Java.
Remember:
"Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, limit its mutability as much as possible."
When you want to create immutable classes than you can use a framework like that: http://immutables.github.io
For examples check this Oracle documentation
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
In a legacy code base I am dealing with, there are vast number of String literals. A large number of them are duplicates. For example, the string "userID" is used say in 500 places. There are maybe a thousand such literals which are used in a repeated manner. IntelliJ Idea static code analysis suggests that I extract those as constants. If the IDE does this refactoring automatically for me, without me typing a single line of code, should I go for it?
Is it a good idea, in general, to extract many such duplicate string literals as constants? This will obviously avoid duplication, will provide single point of access, declaration, etc.
However, some of these literals come into picture when accessed. If I declare all literals as constants (static final), then all those will be loaded together. In that context, is it a good idea to declare all those literals as constants? Could you provide some pointers to garbage collection, memory space precautions in such scenarios? What are best practices used in such scenario?
Some notes: I know that string literals are interned. So I don't thing I would be saving any memory in the worst case. Also it seems that jdk 7 will put those strings in heap rather that permgen. I saw a couple of questions like mine, but feel that it is different. So posting it here.
Thanks
All String Literals are interned automatically. From JDK7+, they will be GCed when the class (actually the classloader which loaded the class which defines the string literal) which defines them gets GCed (provided no other class refers to it (though this happens rarely..). Making them static and final and putting them into a common class is indeed useless from a Memory saving perspective but useful from a design perspective because it will provide a single point of access.
The same String literals are shared across all classes in the JVM. So, there will be no new Strings. Effectively, putting them into one class and accessing them from that place makes your code more structured/ more readable.
My suggestion, don't tinker with legacy code unless it makes a lot of difference. The trade-offs are yours' to choose. :P
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Yesterday I have attended interview in one Leading IT Service company. Technical interview was good, no issues, then I have moved to another set of round about Management, Design and Process. I have answered everything except the below question.
Question asked by interviewer:
Let say you are developing a class, which I am going to consume in my
class by extending that, what are the key points you keep in
mind? Ex, Class A, which has a method called "method A" returns a Collection,
let say "list". What are the precautions you will take?
My Answer: The following points I will consider, such as:
Class and method need to be public
Method 1 returns a list, then this needs to be generics. So we can avoid class cast exception
If this class will be accessed in a multi-threaded environment, the method needs to be synchronized.
But the interviewer wasn't convinced by my points. He was expecting a different answer from me but I am not able to get his thought process, what he was excepting.
So please provide your suggestions.
I would want you holding to design principles of Single Reaponsibility, Open/Close, and Dependency Injection. Keep it stateless, simple, and testable. Make sure it can be extended without needing to change.
But then, I wasn't interviewing you.
A few more points which haven't been mentioned yet would be:
Decent documentation for your class so that one doesn't have to dig too deep into your code to understand what functionality you offer and what are the gotchas.
Try extending your own class before handing it out to someone else. This way, you personally can feel the pain if you class is not well designed and thereby can improve it.
If you are returning a list or any collection, one important question you need to ask is, "can the caller modify the returned collection"? Or "is this returned list a direct representation of the internal state of your class?". In that case, you might want to return a copy to avoid callers messing up your internal state i.e. maintain proper encapsulation.
Plan about the visibility of methods. Draw an explicit line between public, protected, package private and private methods. Ensure that you don't expose any more than you actually want to. Removing features is hard. If something is missing from your well designed API, you can add it later. But you expose a slew of useless public methods, you really can't upgrade your API without deprecating methods since you never know who else is using it.
If you are returning a collection, the first thing you should think about is should I protect myself from the caller changing my internal state e.g.
List list = myObject.getList();
list.retainAll(list2);
Now I have all the elements in common between list1 and list2 The problem is that myObject may not expect you to destroy the contents of the list it returned.
Two common ways to fix this are to take a defensive copy or to wrap the collection with a Collections.unmodifiableXxxx() For extra paranoia, you might do both.
The way I prefer to get around this is to avoid returning the collection at all. You can return a count and a method to get the n-th value or for a Map return the keys and provide a getter, or you can allow a visitor to each element. This way you don't expose your collection or need a copy.
Question is very generic but i want to add few points:
Except the method which you want to expose make other methods and variable private. Whole point is keep visibility to minimum.
Where ever possible make it immutable, this will reduce overhead in mutithreaded environment.
You might want to evaluate if serializability is to be supported or not. If not then dont provide default constructor. And if serializable then do evaluate serialized proxy pattern.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
This applies to both C and JAVA I'm asking for both.
I've got an update loop that's runs maybe a few hundred times a second indefinably.
My concerns are mainly memory management and what happens.
Here's the example so
public methodA(double Delta)
{
double doubleTest = Delta;
SomeObject newObject = new Object(Delta);
}
SomeObject newObject = new Object();
double doubleTest;
public methodB(double Delta)
{
doubleTest = Delta;
newObject.setUpdate(Delta);
}
Now I know in JAVA that the methodA is GC'ed at the cost of performance but what exactly happens in C or C++? Do variables or objects declared within the method scope get destoryed? If so which loop is better? (Would we be getting out of memory with the second loop?)
Also is it really worth pre-creating the object for the method update? What's the performance gain if any?
1. - The variables get destroyed.
2. - Second, if you're passing in a parameter, it does not need to be outside the method scope.
3. - It would be more efficient from a writing-perspective to put it all in one line. The memory footprint is very minimal between the two, if any.
Methods aren't garbage-collected.
I don't see any loops in your code, so I'm confused about what you are asking.
Your two methods do very different things, and so comparing them is difficult. First of all, compilers are very smart these days (Java, C, and C++). Unless Object's constructor has side effects, a reasonable compiler would probably optimize away all calls to methodA anyways, since it does nothing.
methodB does something completely different than methodA, so I'm not sure why you are comparing the two. methodB calls newObject.setUpdate(), which, presuming it has a side effect, will not be removed by the compiler. Of course, if you never actually use newObject anywhere else, the compiler may still determine that it is unnecessary and optimize away all calls to methodB.
In any case, your question is confusing to me because I'm not sure what you are specifically trying to compare.
Now I know in JAVA that the methodA is GC'ed at the cost of
performance but what exactly happens in C or C++? Do variables or
objects declared within the method scope get destoryed? If so which
loop is better? (Would we be getting out of memory with the second
loop?)
There is no concept of method being garbage collected, only references are garbage collected.
Local variables scope is limited to the method/function they are defined in for both Java and c++. But there is an exception to it in c++, if you are creating dynamic data structure using malloc/calloc then the memory of that variable will not freed until you don't explicitly do so. There is no garbage collector in C++ so you need to be careful about dyamic memory allocation and to free that memory. This responsibility lies with the developer in C++, whereas in Java , JVM garbage collector takes care of it.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
As per this answer here
both java objects and primitives go on heap. So from the point of view of JVM, are objects and primitives similar except thaty objects take more space on the heap? In essence, are primitives nothing but 'light' objects?
Java primitives are not "light objects". They are primitives. They fail as objects in two very significant ways: they cannot go into Collection objects and they do not have methods.
They also do not go on the heap, except as fields of an actual Java object. You cannot do new int. Note also that when you declare a local variable that is of a primitive type, the variable comes into existence. When you declare a local variable of an object type, all you get is a reference to an object, but it is set to null and no object of the declared type is allocated by simply declaring the variable.
Note that autoboxing blurs the distinction somewhat, but the distinction is definitely there.
There is a bit of confusion here. The question you're linking to in your question says that primitives inside an object can be in the heap. Primitives can't be in the heap by themselves.
You can't have an int referenced like an object, they are accessed directly without being "dereferenced".
You're extrapolating the fact that primitives could go in heap (as part of other objects) to conclude they could be light-weight objects. A set of primitives make up the state of an Object. They're not objects by themselves.
Primitives just have a value. They don't have a state and behaviour like Objects do. They don't exhibit inheritance, polymorphism etc. They don't behave like entities but like their attributes.