This question, like my previous question, references Effective Java. This time I have quite a few sub-questions.
A privileged client can invoke the private constructor reflectively with the aid of the AccessibleObject.setAccessible() method. If you need to defend against this, modify the constructor.
How, exactly, can a private constructor be invoked? And what is AccessibleObject.setAccessible()?
What approach do you experts follow with singletons?
// Approach A
public class Test{
public static final Test TestInstance = new Test();
private Test(){ ... }
.
.
.
}
// Approach B
public class Test{
private static final Test TestInstance = new Test();
private Test(){ ... }
public static Test getInstance() { return TestInstance; }
.
.
.
}
Isn't the second approach more flexible, in case we have to make a check for new instances every time or the same instance every time?
What if I try to clone the class/object?
a single-element enum type is the best way to implement a singleton.
Why? How?
A priviledged cleint can invoke the private constructor reflectively with the aid of the AccessibleObject.setAccessible method, If you need to defend this, modify the constructor. My question is: How exactly can a private constructor is invoked? and what is AccessibleObject.setAccessible??
Obviously a private constructor can be invoked by the class itself (e.g. from a static factory method). Reflectively, what Bloch is talking about is this:
import java.lang.reflect.Constructor;
public class PrivateInvoker {
public static void main(String[] args) throws Exception{
//compile error
// Private p = new Private();
//works fine
Constructor<?> con = Private.class.getDeclaredConstructors()[0];
con.setAccessible(true);
Private p = (Private) con.newInstance();
}
}
class Private {
private Private() {
System.out.println("Hello!");
}
}
2.What approach do you experts follow with singletons:
...
Typically, the first is favoured. The second (assuming you were to test if TestInstance is null before returning a new instance) gains lazy-loading at the cost of needing to be synchronized or being thread-unsafe.
I wrote the above when your second example didn't assign the instance to TestInstance at declaration. As stated now, the above consideration is irrelevant.
Isn't the second approach more flexible in case we have to make a check for new instance every time or same instance every time?
It's not about flexibility, it's about when the cost of creating the one (and only) instance is incurred. If you do option a) it's incurred at class loading time. That's typically fine since the class is only loaded once it's needed anyway.
I wrote the above when your second example didn't assign the instance to TestInstance at declaration. As stated now, in both cases the Singleton will be created at class load.
What if I try to clone the class/object?
A singleton should not allow cloning for obvious reasons. A CloneNotSupportedException should be thrown, and will be automatically unless you for some reason implement Cloneable.
a single-element enum type is the best way to implement a singleton. Why? and How?
Examples for this are in the book, as are justifications. What part didn't you understand?
Singletons are a good pattern to learn, especially as an introductory design pattern. Beware, however, that they often end up being one of the most over-used patterns. It's gotten to the point that some consider them an "anti-pattern". The best advice is to "use them wisely."
For a great introduction to this, and many other useful patterns (personally, I find Strategy, Observer, and Command to be far more useful than Singleton), check out Head First Design Patterns.
A priviledged cleint can invoke the private constructor reflectively with
the aid of the
AccessibleObject.setAccessible method,
If you need to defend this, modify the
constructor. My question is: How
exactly can a private constructor is
invoked? and what is
AccessibleObject.setAccessible??
You can use java reflection to call private constructors.
What approach do you experts follow with singletons:
I am a fan of using enum to actually do this. This is in the book also. If that's not an option, it is much simpler to do option a because you don't have to check or worry about instance being already created.
What if I try to clone the
class/object?
Not sure what you mean? do you mean clone() or something else that I don't know of?
a single-element enum type is the best way to implement a singleton.
Why? and How?
Ahh my own answer. haha. This is the best way because in this case, the java programming language guarantees a singleton instead of the developer having to check for a singleton. It's almost as if the singleton was part of the framework/language.
Edit:
I didn't see that it was a getter before. Updating my answer to this - it's better to use a function such getInstance because you can control what happens through a getter but you can't do the same if everybody is using a reference directly instead. Think of the future. If you ended up doing SomeClass.INTANCE and then later you wanted to make it lazy so it doesn't load right away then you would need change this everywhere that its being used.
The first rule of the Singleton (Anti-) Pattern is don't use it. The second rule is don't use it for the purpose of making it easy to get at a single instance of a class that you want multiple other objects to share, especially if it is a dependency of those classes. Use dependency injection instead. There are valid uses for Singletons, but people have a tendenecy to badly misuse them because they're so "easy" to use. They make it very difficult to test classes that depend on them and make systems inflexible.
As far as your questions, I think 1, 2 and 3 can all be answered by saying "use an enum-singleton". Then you don't need to worry about constructor accessiblity issues, clone()ing, etc. As far as 4, the above is a good argument for them. I also have to ask, did you read the section in Effective Java that explicitly answers your question?
Example singleton lazy init:
Class main:
public class Main {
public static void main(String[] args) {
System.out.println(Singleton.getInstance("first").value);
System.out.println(Singleton.getInstance("second").value);
System.out.println(Singleton.getInstance("therd").value);
}
}
Class singleton:
public class Singleton {
private static Singleton instance;
public String value;
private Singleton (String s){
this.value =s;
}
public static Singleton getInstance(String param) {
if (instance == null)
instance = new Singleton(param);
return instance;
}
}
When start application, console will contains next strings:
first
first
first
\|/ 73
Related
I sometimes see that people create self instance for example:
public class Example extends Service
{
private static Example mInstance = null;
public void onStart( Intent aIntent, int aStartId )
{
mInstance = this;
.
.
.
}
}
What is the purpose of this?
This is called the Singleton design pattern. Singletons are used when there is going to be a single instance of an object performing operations on non-static data.
See here.
In addition to what other answers put about Singleton pattern, self instances may be used as constants. That's the case of the Color class, that defines an instance for each of the common colours.
http://docs.oracle.com/javase/7/docs/api/java/awt/Color.html
An Android Service (sub)class cannot be a singleton since the framework requires access to a default constructor for the class. The only reason I can think of for keeping a static reference to the (last) instance for which onStart was called is to simplify some internal code that may happen to reside in static methods.
Considering that onStart was deprecated a long time ago (as of API level 5), this is most likely an example of bad coding style from early days of Android.
So that other classes can get an instance and call instance methods on the object. Its frequently used with the Singleton pattern. And for Services and Activities in Android it's a very bad idea- it keeps a reference to the Activity/Service around after it ends, which will cause a memory leak.
In a thread-unsafe singleton pattern implementation, you would have a private constructor, and a public static getInstance method initializing that instance if necessary and returning it.
Here's an example. Note that it is advised to leverage the commodity of a single-element enum instead of the code below, to achieve a "true" singleton.
public class MyThreadUnsafeSingleton {
private static MyThreadUnsafeSingleton instance;
private MyThreadUnsafeSingleton() {
//TODO some ctor logic
}
public static MyThreadUnsafeSingleton getInstance() {
if (instance == null) {
instance = new MyThreadUnsafeSingleton();
}
return instance;
}
}
Final note, there is a variation of the above pattern that is thread-safe across a single classloader through the usage of a nested "holder" class, but that's quite out of scope.
If it has a private default constructor, it's probably a singleton.
If it doesn't, it's something weird.
This sort of layout forces all object instances of this class to share data, regardless of when they are instantiated. The object instance on which OnStart is called will become the underlying data source for any references to this class, regardless of when they were declared or instantiated (before or after OnStart), and regardless of what thread they were created on.
Of course it is always possible there are members of the class that don't bother with mInstance.Member and use this.Member instead. That sort of mixing and matching would probably end up being disastrous.
It's hard to imagine the specific use for this but my guess is that the class is an abstraction of some stateful resource that is global with respect to the process, e.g. a form/window or a web service client that caches its credentials. Could be anything though.
If this code was written around 2003-2005 (early c# days) I'd guess that it is a sloppy implementation of a Singleton-- it was sort of in vogue back then as design patterns were becoming a thing and Singleton was the example in all the textbooks. Turns out it's a horrible pattern for dependency injection and mocking, so these days this pattern doesn't get used as much.
This paradigm is often used for objects that are heavy or slow to construct and only one is needed.
public class Server {
private static Server server = null;
// Stop them making their own.
private Server () {
// Heavyweight stuff.
}
public static Server getServer () {
if ( server == null ) {
// Heavy constructor.
server = new Server();
}
return server;
}
}
In a multi-thread environment it is usually combined with the singleton design pattern.
This might just be a question of personal taste and workflow, but in case it's more than that, I feel I should ask anyway.
In Java, what differences are there between creating an instance via constructor and via a static method (which returns the instance)? For example, take this bit of code from a project I'm working on (written up by hand at time of posting, so some shortcuts and liberties are taken):
Plugin main;
Map<int, int> map;
public Handler(Plugin main) {
this.main = main;
}
public static Handler init(Plugin main) {
Handler handler = new Handler(main);
handler.createMap();
}
public void createMap() {
this.map = Maps.newHashMap();
}
In cases like this, what would the difference be between using
Handler handler = new Handler(this);
and
Handler handler = Handler.init(this);
in the Plugin class, besides the fact that createMap() runs only in the latter because it's not called in the constructor?
To clarify, in this case, Plugin is considered the main class.
I know enough Java syntax to be able to write intermediate-level plugins, but not enough about Java itself to know the difference between these two ways of doing this.
EDIT: For instance, the Maps class that I used to create the Map uses a static factory method (I hope I'm using that term correctly) called using the class instead of an object.
There are both advantages and disadvantages of static factory methods.
Advantages
Descriptive, meaningful names.
When invoked they can decide whether to return a new instance
They can return an object of any subtype of the return type
They reduce the verbosity of creating parameterized type instances
Disadvantages
If you provide only static factory methods, classes without public or protected constructors cannot be subclassed
They are not readily distinguishable from other static methods
Source: Effective Java, Second Ed.
The difference is a static factory method is more flexible. It can have all sorts of ways to return an instance. It can do other side stuff. It can have a more descriptive name. It can be invoked by its simple name (e.g. foo(args)) by static import or inheritance.
The constructor call is more certain - the caller knows exactly what's happening - a new instance of that exact class is created.
it might be stupid question, but I dont know the answer to it and I dont know where to search the answer, so it would be nice if someone could help me.
I've a class (lets name it A) with different members and methods. I use the methods of this class in another class (lets name it B).
For every B-Object created I want to use the SAME instance of A. Is that possible?
Actually I have a constructor in B where I call A a = new A(); Of course I always get different instances of this class.
How can I now change this? I know it could be possible to solve it with spring framework (inject always the same object into the instances of B), but I cant use it. How else could this problem be solved?
Thank you very much for your help! :-)
Yes its possible. You need to define a singleton instance of classA that is static, and use it wherever you want.
So there are multiple ways of doing this:
public class ClassA {
public static ClassA classAInstance = new ClassA();
}
then anywhere you can do
ClassA.classAInstance.whatever();
This is simple, but it might be enough for you.
If you really want to use the singleton pattern, look here for a Java example. The advantage of this approach is that it makes sure that you only have 1 classA instance.
To elaborate on other answers:
public class A
{
private static A instance;
private A()
{
...
}
public static A getInstance()
{
if (instance == null)
instance = new A();
return instance;
}
...
public void doSomething()
{
...
}
}
And then call in B like this:
A.getInstance().doSomething();
It sounds like you may want A to be a Singleton.
In software engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object.
This means your existing code will have to modified to use some kind of getInstance() method, but once that change has been made all instances of class B will use a single instance of class A.
Here is a direct link to the: simplest example from the above site.
Just use a static class and make sure it's public.
Though you can use singleton design pattern to share the same instance every-time but if you want to use a same instance with parameters(overloaded constructor)..you cannot use SINGLETON
I am looking at a codebase and I often see something like:
public class SomeClass
{
protected static SomeClass myObject;
//...
public static SomeClass getObject()
{
return myOjbect
}
}
I'd like to make sure I understand the purpose behind this. Is it to ensure one instance of the class gets shared even if it is instantiated multiple times? I am not sure about the vocabulary here, or else I'd search for the answer, so if this pattern has a name, please let me know.
Also, this seems a little chicken-and-egg definition because the class includes an object of the type of the class. Why isn't this actually paradoxical?
Thanks!
This is really only common with the Singleton Pattern where there is only this one instance of the class. While it has its uses, Singleton is over- and misused more often than not (usually to disguise procedural programming as OO). It also occurs very often in example code for Java AWT or Swing, where you typically subclass Frame / JFrame, and create an instance in a main method inside the same class.
Also, this seems a little
chicken-and-egg definition because the
class includes an object of the type
of the class. Why isn't this actually
paradoxical?
Why do you think it is? The class mainly describes what members instances of this type have - but a static member does not belong to an instance, it belongs to the class itself, so it doesn't have anything to do with the "blueprint" role of the class. Static members are really somewhat un-OO because of that.
But even on the instance level you can have references of the same type. For example, an entry in a linked list would typically have two references to the next and previous entries, which are of the same class.
This is called the Singleton design pattern.
You are correct in stating that the purpose is to ensure only one instance of the class gets created.
Wikipedia has a preyty good article on the pattern.
The pattern you mentioned is called "Singleton", but from your code sample it is not clear if this is really what is intended. Due to the fact that the member is protected, I would guess not - if there are subclasses, then there would probably not be a single instance.
It's called Singleton. You ensure the creation of just ONE (1) object of a given class.
You should add a private Constructor, so the only one who create the object is the class.
public class SomeClass
{
// Using private constructor
protected static SomeClass myObject = new SomeClass();
private SomeClass(){
//...
}
public static SomeClass getObject()
{
return myOjbect
}
}
Much much more here, in Wikipedia
You may want to take a look to Factory Pattern
It's not all that uncommon; it can be a good way to implement the Singleton pattern. There can be other uses as well - sometimes you will want a handful - and no more - of objects of a given class; that class is a good place to hang onto them. In the event that you don't want other classes to be able to create objects of this class, it is common to give the class a private constructor as well.
It's not paradoxical, because the compiler can be aware of a reference to the class before it has fully compiled the class. Later - if you like to think of it this way - it can "fill in the blanks".
I know this is normally rather stupid, but don't shoot me before reading the question. I promise I have a good reason for needing to do this :)
It's possible to modify regular private fields in java using reflection, however Java throws a security exception when trying to do the same for final fields.
I'd assume this is strictly enforced, but figured I'd ask anyway just in case someone had figured out a hack to do this.
Let's just say I have an external library with a class "SomeClass"
public class SomeClass
{
private static final SomeClass INSTANCE = new SomeClass()
public static SomeClass getInstance(){
return INSTANCE;
}
public Object doSomething(){
// Do some stuff here
}
}
I essentially want to Monkey-Patch SomeClass so that I can execute my own version of doSomething(). Since there isn't (to my knowledge) any way to really do that in java, my only solution here is to alter the value of INSTANCE so it returns my version of the class with the modified method.
Essentially I just want to wrap the call with a security check and then call the original method.
The external library always uses getInstance() to get an instance of this class (i.e. it's a singleton).
EDIT: Just to clarify, getInstance() is called by the external library, not my code, so just subclassing won't solve the issue.
If I can't do that the only other solution I can think of is to copy-paste entire class and modify the method. This isn't ideal as I'll have to keep my fork up to date with changes to the library. If someone has something a little more maintainable I'm open to suggestions.
It is possible. I've used this to monkeypatch naughty threadlocals that were preventing class unloading in webapps. You just need to use reflection to remove the final modifier, then you can modify the field.
Something like this will do the trick:
private void killThreadLocal(String klazzName, String fieldName) {
Field field = Class.forName(klazzName).getDeclaredField(fieldName);
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
int modifiers = modifiersField.getInt(field);
modifiers &= ~Modifier.FINAL;
modifiersField.setInt(field, modifiers);
field.set(null, null);
}
There is some caching as well around Field#set, so if some code has run before it might not necessarily work....
Any AOP framework would fit your needs
It would allow you to define a runtime override for the getInstance method allowing you to return whatever class suits your need.
Jmockit uses the ASM framework internally to do the same thing.
You can try the following. Note: It is not at all thread safe and this doesn't work for constant primitives known at compile time (as they are inlined by the compiler)
Field field = SomeClass.class.getDeclareField("INSTANCE");
field.setAccessible(true); // what security. ;)
field.set(null, newValue);
You should be able to change it with JNI... not sure if that is an option for you.
EDIT: it is possible, but not a good idea.
http://java.sun.com/docs/books/jni/html/pitfalls.html
10.9 Violating Access Control Rules
The JNI does not enforce class, field,
and method access control restrictions
that can be expressed at the Java
programming language level through the
use of modifiers such as private and
final. It is possible to write native
code to access or modify fields of an
object even though doing so at the
Java programming language level would
lead to an IllegalAccessException.
JNI's permissiveness was a conscious
design decision, given that native
code can access and modify any memory
location in the heap anyway.
Native code that bypasses
source-language-level access checks
may have undesirable effects on
program execution. For example, an
inconsistency may be created if a
native method modifies a final field
after a just-in-time (JIT) compiler
has inlined accesses to the field.
Similarly, native methods should not
modify immutable objects such as
fields in instances of
java.lang.String or java.lang.Integer.
Doing so may lead to breakage of
invariants in the Java platform
implementation.
If you really must (though for our problem I'd suggest you use the solution of CaptainAwesomePants) you could have a look at JMockIt. Although this is intented to be used in unit tests if allows you to redefine arbitrary methods. This is done by modifying the bytecode at runtime.
I will preface this answer by acknowledging that this is not actually an answer to your stated question about modifying a private static final field. However, in the specific example code mentioned above, I can in fact make it so that you can override doSomething(). What you can do is to take advantage of the fact that getInstance() is a public method and subclass:
public class MySomeClass extends SomeClass
{
private static final INSTANCE = new MySomeClass();
public SomeClass getInstance() {
return INSTANCE;
}
public Object doSomething() {
//Override behavior here!
}
}
Now just invoke MySomeClass.getInstance() instead of SomeClass.getInstance() and you're good to go. Of course, this only works if you're the one invoking getInstance() and not some other part of the unmodifiable stuff you're working with.
with mockito is very simple:
import static org.mockito.Mockito.*;
public class SomeClass {
private static final SomeClass INSTANCE = new SomeClass();
public static SomeClass getInstance() {
return INSTANCE;
}
public Object doSomething() {
return "done!";
}
public static void main(String[] args) {
SomeClass someClass = mock(SomeClass.getInstance().getClass());
when(someClass.doSomething()).thenReturn("something changed!");
System.out.println(someClass.doSomething());
}
}
this code prints "something changed!"; you can easily replace your singleton instances. My 0.02$ cents.
If there is no external hack available (at least I am not aware of) I would have hacked the class itself. Change the code by adding the security check you want. As such its an external library, you won't be taking the updates regularly, also not many update happens anyway. Whenever that happens I can happily re-do it as it is not a big task anyway.
Here, your problem is good-old Dependency Injection (aka Inversion of Control). Your goal should be to inject your implementation of SomeClass instead of monkeypatching it. And yes, this approach requires some changes to your existing design but for the right reasons (name your favorite design principle here) - especially the same object should not be responsible for both creating and using other objects.
I assume the way you're using SomeClass looks somewhat like this:
public class OtherClass {
public void doEverything() {
SomeClass sc = SomeClass.geInstance();
Object o = sc.doSomething();
// some more stuff here...
}
}
Instead, what you should do is first create your class that implements the same interface or extends SomeClass and then pass that instance to doEverything() so your class becomes agnostic to implementation of SomeClass. In this case the code that calls doEverything is responsible for passing in the correct implementation - whether be the actual SomeClass or your monkeypatched MySomeClass.
public class MySomeClass() extends SomeClass {
public Object doSomething() {
// your monkeypatched implementation goes here
}
}
public class OtherClass {
public void doEveryting(SomeClass sc) {
Object o = sc.doSomething();
// some more stuff here...
}
}