aspose file tools*
The moose likes Beginning Java and the fly likes Why make a Globally shared instance of a Class ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why make a Globally shared instance of a Class ?" Watch "Why make a Globally shared instance of a Class ?" New topic
Author

Why make a Globally shared instance of a Class ?

justin smythhe
Ranch Hand

Joined: Jul 06, 2012
Posts: 107
What are the benefits ? What are the disadvantages ?
Greg Brannon
Bartender

Joined: Oct 24, 2010
Posts: 561
Is this a homework essay question?

Either way, can you explain what "globally shared" means, give an example, and explain why you think having such a class might be useful?


Always learning Java, currently using Eclipse on Fedora.
Linux user#: 501795
justin smythhe
Ranch Hand

Joined: Jul 06, 2012
Posts: 107
Greg Brannon wrote:Is this a homework essay question?
Either way, can you explain what "globally shared" means, give an example, and explain why you think having such a class might be useful?


Not a homework question. It came up when I was peeking at some non-java 1.6 api classes.
It can save memory if a lot of other objects use it. I can't think of any other reasons.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61426
    
  67

Do you mean a Singleton?


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Greg Brannon
Bartender

Joined: Oct 24, 2010
Posts: 561
Which "non-java 1.6 api classes?"
justin smythhe
Ranch Hand

Joined: Jul 06, 2012
Posts: 107
Bear Bibeault wrote:Do you mean a Singleton?

No, no the singleton pattern. I mean something like this :

private static final MyClass forEveryoneToUse = new MyClass();

....more code here.
justin smythhe
Ranch Hand

Joined: Jul 06, 2012
Posts: 107
Greg Brannon wrote:Which "non-java 1.6 api classes?"


Why do you ask this question ?
Bill Gorder
Bartender

Joined: Mar 07, 2010
Posts: 1666
    
    7

One well established idiom for this is Logger declaration



Globally shared is probably a poor description for this as your example you posted is actually private.

Consider the modifiers one at a time

private - only available to this class
final - can not be reassigned
static - Only one reference per class

Advantages?

1. less CPU overhead: loggers are retrieved and assigned only once, at hosting class initialization
2. less memory overhead: logger declaration will consume one reference per class


[How To Ask Questions][Read before you PM me]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why make a Globally shared instance of a Class ?