Can objects have access modifiers? - java

I was going through a piece of code when I came across this:
public class ClassicA {
private static ClassicA instance = null;
}
I have never used such a thing and wanted to know what it means and how it is used. Also, what is the purpose of the access modifier for the object? Any examples/links are welcome.

It probably means that ClassicA is a Singleton. It is usually involved with declaring a private constructor, and a single public static getInstance() method.
Singletons are used when you want to make sure there is only one global instance of ClassicA in your entire application. Instead of instantiating it, you call getInstance(), which will check if it was instantiated once or not. If it was, it will instantiate it, and store the the resulting object in the private instance field. If it was already constructed, just return the instance field without re-instantiating.
Note that this is considered bad practice. See: https://softwareengineering.stackexchange.com/questions/40373/so-singletons-are-bad-then-what

Well, the class ClassicA has a private and static field instance which is null.
If there are no getters/setters the only way to access that field would be using reflection.
Since this looks like a singleton, I guess there's a getter as well that returns instance and if it is null first creates an instance and assigns it to the field.

It's a (static) member of the class, and yes, these can have access modifiers. (And as others have noted, it indeed looks like a portion of a Singleton.)

its a singleton
basically the author intended there to be only 1 instance of this class alive (the instance field)
the constructor is probably private and used only within the class.

This is used typically for a class that exhibits the Singleton design pattern.
The point is that for these types of objects you only want a single instance at most. What you do is create a private constructor for the class and then usually a public static method called, getInstance in which you check if the private instance variable has been set yet or not. If it has not yet set, you create a new instance of the class and assign it to instance, then you return that instance. If the object was already created you simply return it. Like this:
public class MySingleton {
private static MySingleton instance=null;
private MySingleton() {
//do stuff
}
public static MySingleton getInstance() {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}
}
Then from throughout your program you can easily get the singleton object from anywhere.
Thus, a singleton is effectively just a glorified global variable in languages such as PHP. I would argue though that it is a lot cleaner as you can prevent others from reassigning the reference to the instance and other trickery that may be very bad from a design standpoint.
Typically people use it for classes that manage some type of data access, such as a DB object, for Factory classes and builder classes, see this for more info

This is used for singleton pattern. See here

private static means that the instance is available to all the instances and static methods of the class, but only to them. It's actually like having static private method.
Such tricks can be used for example for implementing a singleton: you keep internally a single instance of a class, and you can give it to the class's clients on demand. Or for any other case when you need something shared just between the static methods and instances of some class.

Related

Correct implementation of initialization-on-demand holder idiom

I have got two versions of "Initialization-on-demand holder idiom":
http://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom
http://en.wikipedia.org/wiki/Singleton_pattern#The_solution_of_Bill_Pugh
The major difference between above is that the first one declared INSTANCE as private, but the second one declared INSTANCE as public.
Please tell me which one should I use.
Sorry, I have not found the difference between using private and public in my application:
public class Singleton {
private int x;
public int getX() {
return x;
}
private Singleton () {}
private static class LazyHolder {
//both private and public works
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return LazyHolder.INSTANCE;
}
}
The only thing I do is to call something like Singleton.getInsance().getX(), so both versions works.
Thus I want to know the situations for using them.
There are several things to explain about singletons and the initialization-on-demand holder idiom. Here we go:
1) The access modifier:
Normally you can't access fields and methods in another class if they are private. They must at least be package private (having no modifier, it is) if the accessing class is in the same package. So the correct way to implement it, would be:
public class Singleton {
...
private static class LazyHolder {
static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return LazyHolder.INSTANCE;
}
}
However, JLS 6.6.1 explains:
Otherwise, if the member or constructor is declared private, then access is
permitted if and only if it occurs within the body of the top level class (ยง7.6)
that encloses the declaration of the member or constructor.
That means, declaring the field INSTANCE as private still allows the access from inside the top level class Singleton. But the compiler must do some tricks to get around the private modifier: It inserts package private methods for getting and setting such a field.
In fact, it does not matter, which modifier you place on it. If it is public, it still cannot be accessed from other classes than Singleton. However ... I think the package private access is the best. Making it public does not makes sense. Making it private forces the compiler to do some tricks. Making it package private reflects what you have: Access to a class member from another class.
2) How to implement a singleton:
If you ever want to consider serialization, the singleton implementation will get a bit difficult. Joshu Bloch wrote a great section in his book "Effective Java" about implementing singletons. At the end, he concluded to simply use an enum for this, as the Java enum specification provides every charecteristic that is needed in regards to singletons. Of course, that does not use the idiom anymore.
3) Considering design:
In most design decisions, singletons do not have their places anymore. In fact, it could indicate a design issue, if you must place a singleton into your program. Keep in mind: Singletons provide a global acess mechanism to some data or services. And this is not OOP.
private static class LazyHolder {
$VISIBILITY static final Singleton INSTANCE = new Singleton();
From a consumer's point of view it does not really matter if $VISIBILITY is public or private because the LazyHolder type is private. The variable is only accessible via the static method in both cases.
I use number 1 (private INSTANCE) because you generally try to use the narrowest scope as possible. But in this case since the Holder class is private it doesn't really matter. However, suppose someone later decided to make the Holder class public then number 2 could be problematic from an encapsulation perspective (callers could bypass the getInstance() method and access the static field directly).

How to check if there is any instance of a class at runtime?

Is there any method to check whether any instance of a class is running?
I have a GUI and I don't want open another instance of it, if a one is already running.
I know about including a counter in constructor. Any method except that?
Thanks in advance!!
Use the singleton pattern.
Here is a simple implementation in java of a singleton:
public class MyClass {
private static MyClass INSTANCE = new MyClass();
private MyClass() { // private constructor prevents creation outside class
}
public static MyClass getInstance() {
return INSTANCE;
}
}
Note that this is not "bulletproof" (there are "hacks" you can use via reflection to circumvent this and create two instances), however if you're the only user of the code it will be fine.
Is there any method to check whether any instance of a class is running?
The simple answer is No.
The normal way to deal with this problem is to use the Singleton design pattern. The idea of the pattern is that you write the code to remove the possibility of creating multiple instance of the class.
In Java you typically do this by declaring the class constructor to be private, and providing access to the singleton instance via a static method. Depending on your precise requirements, the singleton can be created eagerly or lazily.
Bohemian's answer provides a good example of this approach.
(In Java 5 or later, it is also possible to use enum types to implement singletons.)
Use Enum as recommended by J. Bloch (Effective Java Programming 2nd Ed., Addison Wesley)

Creating a static reference versus a singleton

I am using the java driver for mongodb, and the documentation says to:
"you should create a single Mongo instance, and you can use it in every request."
Using a single instance sounds like a singleton.
In other places for a different library I have read the instructions saying that I should create a static reference as it is thread-safe.
Can someone explain the differences between a singleton and creating a static reference?
So the actual code that I need to instantiate either statically or via a singleton would be:
Mongo m = new Mongo( "localhost" , 27017 );
Can someone explain both methods and the underlying differences if any?
In Java you typically use a static variable to implement the Singleton pattern.
http://java.sun.com/developer/technicalArticles/Programming/singletons/
Singleton is a design pattern where you have one instance of an object shared amongst the rest of your code. Static variables are a Java language feature.
In order to implement a Singleton, you would usually use static variables.
You have 3 issues: singleton, static reference and thread-safety.
You have a singleton if you can only create one instance of a class. That's useful since things would get messed up if you had two instances of Mongo running. However, you cannot implement the singleton design pattern for Mongo in your code: you can call new Mongo() anywhere you want and create as many instances as you want. You just have to be careful you don't do so, but it shouldn't be very hard.
To implement a singleton, the class designer will very often use a static reference as follows:
public class MyClass {
private static final MyClass SINGLETON = new MyClass();
private MyClass() {...} // !!private, not accessible
public MyClass getSingleton() { return SINGLETON; }
}
And you will only ever have one single instance of MyClass since the constructor is private and the only way to get an instance is through MyClass.getSingleton(). Obviously the Mongo designer would have had to design the Mongo class as such; there is nothing you can do to make it a singleton.
As far as thread-safety is concerned, I don't quite see the link with singleton. A singleton class must be made thread-safe: if many threads change and read the state of a singleton, you need proper synchronization to make sure all threads see the same values. I don't know Mongo, but I would bet it is a thread-safe class.
Use the Singleton pattern on an object if you only want to be passing around a single instance of this object to other objects and methods that need to use this single instance. Use a static reference if you only want to be using the object's class statically (i.e as a static reference).
If only one class is using your singleton object there is no visible difference in number of objects created.
Assuming you need an object of classASing using Singleton approach
ClassASing {
private static ClassASing obj = new ClassASing();
private ClassAsing(){...}
public static ClassASing getNewObject(){
return obj;
}
}
Using Singleton approach
ClassB{
private ClassASing singObj = ClassASing.getNewObject();
}
no matter how many instances of ClassB created all of them will be using the same object of ClassASing
using static reference
ClassB{
private static ClassA sObj = new ClassA();
}
* no matter how many instances of ClassB created all of them will be using the same reference pointing to the same object.
Not much difference here 1 object being used in both the cases.
Now if u consider another sencario that you need object in two of your classes.
singleton approach
ClassB1{
private ClassASing singObj1 = ClassASing.getNewObject();
}
ClassB2{
private ClassASing singObj2 = ClassASing.getNewObject();
}
no matter how many instances of ClassB1 created all of them will be using the same object of ClassASing
no matter how many instances of ClassB2 created all of them will be using the same object of ClassASing that ClassB1 is already using so only one object of ClassASing
Static reference approach
ClassB1{
private static ClassA sObj1 = new ClassA();
}
ClassB2{
private static ClassA sObj2 = new ClassA();
}
no matter how many instances of ClassB1 created all of them will be using the same reference sobj1 pointing to the same object
no matter how many instances of ClassB2 created all of them will be using the same reference sobj2 pointing to the same object but this object is different from the one created in ClassB1 so now you have two objects of ClassA.

How do I find where an instance of a Java singleton is created?

In a large, complex program it may not be simple to discover where in the
code a Singleton has been instantiated. What is the best approach to keep track of created singleton instances in order to re-use them?
Regards,
RR
A Singleton usually has a private constructor, thus the Singleton class is the only class which can instantiate the one and only singleton instance.
It's the responsibilty of singleton class developer to make sure that the instance is being reused on multiple calls.
As a user, you shouldn't worry about it.
class Singelton
{
private static Singelton _singelton = null;
private Singelton()
{
}
// NOT usable for Multithreaded program
public static Singelton CreateMe()
{
if(_singelton == null)
_singelton = new Singelton();
return _singelton;
}
}
Now, from anywhere in your code, you can instantiate Singelton, how many times you like and each time assign it to different reference. but c'tor is called ONLY once.
I would use an enum
enum Singleton {
INSTANCE:
}
or something similar which cannot be instantiated more than once and globally accessible.
General practice for naming methods which create/return singletons is getInstance(). I don't understand the situation when you can't find the place in code where singletons created, but you can search for this method name.
If you want to catch the exact moment of singleton creation - you can use AOP. AspectJ is a good example in java. You will be able to execute your code before/after creation of class or calling getInstance() method.
If your question is about reusing of created Singletons, then search this site. For example

How to pass a singleton reference to ten sibling objects

If ten classes inherit from a base class, and all ten of the subclasses need access to a singleton, how should the reference to the singleton be passed. I see several ways of going about this, two such being:
Call a static method in the superclass that sets the reference of a static object which can then be shared by the subclasses
Pass a reference of the singleton to each subclass as an argument in their constructors. Each subclass could store a reference to the singleton object, or pass it into the superclass constructor.
But I don't know what is the preferred way, or if I am missing something obvious. Thanks in advance.
Why not use the getInstance() method in your singleton class? You don't need to pass it along. Whenever you need it use the static getInstance() method.
Option 1 provides for less noise and duplication in your code.
How about creating singleton instance in base class like this:
static final MySingleton mySingleton = new MySingleton();
mySingleton is then automatically available in all the inherited classes.
EDIT: As per your comment:
You can get the static reference in base class (if it doesn't require passing runtime argument) like this:
static final MySingleton mySingleton;
static {
SomeClass so = new SomeClass(123, "abc");
mySingleton = so.getMySingleton();
}

Categories