• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to create a new (different) object everytime by a method?

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,

I have created a Singleton Class here.



OUTPUT:1284693
It outputs the same hashcode everytime and yes it is Valid as according to singleton concept but,
The next Class which is defined below,


OUTPUT: 1284693
this also outputs same hashcode why?

question 1) i have not used static modifier in the method here then also it is returning the same object?

question 2) If this code is wrong then, how to create a method that return new object everytime?

thanks!
 
Saloon Keeper
Posts: 15489
363
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You have not created a singleton, because you return a new object every time the singleton is requested. Hash codes can only help you determine that a class is NOT singleton, not that it IS.

To create a singleton, you need to save the one and only instance of that type in the application scope. You can do that with a static variable, or by creating only one instance of that type, and passing it to the rest of the application. The latter is the only correct way to do it if the singleton is mutable. For immutable types, rather than using a regular class, use an enum:
 
Marshal
Posts: 79153
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Aditya Soni wrote:. . . OUTPUT:1284693
It outputs the same hashcode everytime and yes it is Valid as according to singleton concept but,
. . .
OUTPUT: 1284693
this also outputs same hashcode why?
. . .

Not if you call the singleElement method twice, it doesn'tI would go further than Stephan and say that an enum is the preferred way to create a singleton, unless you want it mutable. Of course there is considerable doubt about whether the singleton really is a pattern or an anti‑pattern.
You cannot tell why the different classes return the same hash code from their instances; it does however show that same hash code does not imply same object.
 
Stephan van Hulst
Saloon Keeper
Posts: 15489
363
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As you can see in the example that uses a mutable singleton, SomethingThatRequiresSingletons doesn't actually care whether only one instance of MutableSingleton is created, as long as it receives one to work it. This perfectly displays why having singletons in the first place is very questionable application design.
 
Aditya Soni
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Guys,

Firstly please solve my silly doubt i.e,
Why there is same hashcode in every method calling? or It meant to be different objects but JVM store the object to that hascode everytime?
 
Stephan van Hulst
Saloon Keeper
Posts: 15489
363
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hash codes are not required to be different for different objects. The default implementation just uses some kind of memory address as the hash code of an object, so if you don't change when and where the object is created, the JVM will likely assign it the same relative memory address.

It doesn't really matter. Hash codes aren't interesting at all if you're working with singleton types.
 
Rancher
Posts: 4801
50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, I ran the two of them and I got 1510467688 for both.

The hash code is a memory location in the JVM, in the case of the Object.hashCode method.
Since both examples use the same settings for the JVM then there's no reason I can think of for it not to be the same.

If I stick:

before the current code in main() then 'foo' has the same hash code as above, and the other object (Singleton or Multiple) has a different one.
 
Campbell Ritchie
Marshal
Posts: 79153
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Dave Tolls wrote:. . . The hash code is a memory location in the JVM, in the case of the Object.hashCode method.

That implementation is nowhere defined. The API documentation says that is what happens typically, so it might not apply in every case. Obviously nobody is going to change that in a hurry: if it ain't broke, don't fix it.

. . . there's no reason I can think of for it not to be the same. . . .

Agree with that. I did manage to get the same hashCode from instances of different classes yesterday, so my current JVM is probably behaving as you said.
 
Dave Tolls
Rancher
Posts: 4801
50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As you say, there's no guarantee that it will stay that way.
It's more a case of, currently, being an interesting (though unimportant) quirk of the algorithm it uses to assign things to the heap (I expect).
 
Campbell Ritchie
Marshal
Posts: 79153
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
But JDK8u122 might allocate memory in a different manner, so the first object created resides in a different location, so those hash codes would differ even if memory is used to calculate the hash code. All it needs is a few more Class files of different sizes loaded at start‑up.
 
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Aditya Soni wrote:
Why there is same hashcode in every method calling? or It meant to be different objects but JVM store the object to that hascode everytime?


Treat hashCode values as relatively arbitrary numbers with guarantees as defined by the API contract during an execution of a Java application; that means the same execution.

You mustn't read more into the meaning of a hashcode than what the API says. In particular, you are only guaranteed the same hashCode value "during an execution of a Java application" iff (if and only if) two or more objects are equal according to the equals(Object) method. Your expectation of getting a different hashCode just because the object's class is different is not reasonable since you're talking about separate executions of the Java application. It could very well be the case that the Java VM is using the same memory location to calculate the hashCode for those particular objects and if you're getting the same hashcode value on each run, it's likely that those objects just happen to occupy the same address because that's just how the program happens to get loaded into memory each time you run the application.  Again, the key here is that these are separate executions so the hashcode of an object in one execution has absolutely nothing to do with the hashcode of a different object in a different execution.

Also, your idea that Java stores an object in "that hashcode" is not correct. Java does no such thing. If a class does not override Object.hashCode(), then the hashcode will be calculated based on the object's memory location.  However, if the hashCode() method is properly overridden, then the hashCode value may have nothing to do all with the object's location in memory.
 
Aditya Soni
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
so finally i am stating that:-
in the method getSingleObject() which "static" is returning me a single object everytime i make a call to it.
and the method multipleObject() which is not static is returning new object everytime i make i make a call to it.

is that correct?
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ironically, those statements are technically correct but you still do NOT have a correct understanding of what is happening. Both the static and non-static methods in your code do the exact same thing because except for the class that is being instantiated, the code is identical! Both methods return a single object. Both methods return a NEW object each time they are invoked. With both methods, if you invoke them multiple times, you will create multiple new instances of objects.

The fact that one is static and the other one isn't has NOTHING to do with whether they will return a singleton instance. Neither of those methods will do that because your code has no singleton. Saying that "the method returns a single object" is NOT the same as saying "the method returns a singleton" and your code is in fact doing the former, not the latter.
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Think of it this way: there are two guys. The first guy has a bucket with a large number of pennies in it. When you ask him to give you a penny, he will give you a single penny. When you again ask him to give you a penny, he will give you yet another single penny. So, each time you ask him for a penny, he only gives you a SINGLE penny but it's a different penny that he has taken from his bucket of pennies each time. That's what both of your methods do.

Let's look at the second guy. This guy doesn't have a bucket of pennies. He only has one single, I.e., solitary penny. Only this penny is magical. This is how: When you ask this guy to give you a penny, he will gladly hand you the ONE SINGLE penny that he has. The next time you ask this guy for a penny, the penny that he gave you before magically disappears from your pocket and reappears in his hand. Then he will give that same penny to you again. Each subsequent time you ask the guy for a penny, the same thing happens: the penny disappears from your pocket and reappears in his hand and then he gives it right back to you.

With the first guy, you can potentially end up with lots of single pennies in your pocket. With the second guy, you will only ever have that one singleton penny in your possession.

Your code in both methods is the first guy. You don't have code for the second guy with the magic penny.
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you don't believe in magic and still don't understand the concept, here's another way to look at it.

There's a joke about selling the Brooklyn Bridge in Manhattan. Just look it up if you don't know the joke. Anyway, if you try to sell the Brooklyn Bridge, you can't sell multiple bridges because there's only one Brooklyn Bridge. You'd have to just sell "ownership" of the bridge. You could sell ownership to multiple people (thus committing fraud on a larger scale) but still there would only ever be ONE Brooklyn Bridge. That's what a Singleton is. In a program, there can be multiple references to a Singleton but there will only ever be ONE instance of it in memory.

On the other hand, if you sold T-Shirts of a particular kind, then you can sell multiple instances of that T-Shirt. Each one you sell is the same as all the other ones you sold but at the same time, each one you sell is a different T-Shirt. In the end, many people will have the same kind of T-Shirt that you sold to them but they will each have their own "instance".  That's what both your methods do because each time you call them, you construct a new object and return it to the caller.

Again, your code does not have a singleton. You only have factory methods that produce single objects each time you call them.
 
Campbell Ritchie
Marshal
Posts: 79153
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It works a lot better on this side of the Pond; you try to sell London Bridge and American millionaires think you are selling Tower Bridge which is much prettier. They are easy enough to move, except for the weight of traffic since both carry major roads. Or are you telling use that the Singleton Pattern is nearly as much of a scam as selling XYZ Bridge? Or are you angling for cows? Because I might buy some cattle for those two examples
 
Aditya Soni
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you so much for your effort to make me understand what exactly is singleton and factory methods.
Now i got it the difference but, as you stated that,


Junilu Lacar wrote:

Again, your code does not have a singleton. You only have factory methods that produce single objects each time you call them.



There is what i am stucking again.

If my code for singleton method is wrong then,
What is the correction i have to do to achieve singleton class that has method which return only SINGLE PENNY(OBJECT) each time.
as i have read this on (http://www.javatpoint.com/singleton-design-pattern-in-java&grqid=C71jFPsN&hl=en-IN) about design patterns of singleton.
The code i have written is i get from here.

Please correct me for the write code for singleton class?(easy go )
Thanks again all for the efforts.


 
Ranch Hand
Posts: 514
1
Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
To create Singleton class you need to write it this way:


This ensures that only one instance of Singleton class is created.
 
Campbell Ritchie
Marshal
Posts: 79153
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Bin Smith wrote:. . . This ensures that only one instance of Singleton class is created.

Have you tested that code? There is an error in your design which will ensure that no instances are ever created.
 
Aditya Soni
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator




Is this correct design for a singleton class?
Is object here is single and same everytime?
 
Stephan van Hulst
Saloon Keeper
Posts: 15489
363
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No, not if your goal is for it to be thread-safe. You're using the double-checked locking idiom, which is broken. It is possible for one thread to get an instance of A before its constructor has finished running.

Like Campbell and I already mentioned, the best way to create a singleton is with an enum:

However, the bigger question is why do you need a singleton in the first place?
 
Aditya Soni
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
okay now i got it.

your code is a bit tough to understand for me at first but i will go thru it again.

and yeah i am just gaining knowledge about Singleton Concept as it is very important perspective in interview purposes
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Aditya Soni wrote:and yeah i am just gaining knowledge about Singleton Concept as it is very important perspective in interview purposes


Any sane professional these days should be wary of overusing and abusing the Singleton pattern. Anyone who goes into an interview, whether that's the applicant or the interviewer, thinking that Singleton is a "good thing" to use is sadly misinformed. It's good to know about Singleton but it's better to know its pros and cons, how it should be properly used, and how it is often abused by naive programmers.

If I remember correctly, even one (or more?) of the authors of the Gang of Four book (THE design patterns book) was said to have publicly written that he (they?) regrets having included Singleton at all since it has become so widely abused and misused. Don't quote me on this though, go research it yourself: Pros and Cons of Singleton Pattern
 
Aditya Soni
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Oh really, anyway i got some learning.
Thanks all for the answers.
 
If you believe you can tell me what to think, I believe I can tell you where to go. Go read this tiny ad!
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic