Abstract int() causing an invisible halt in my application - java

I noticed today that a certain feature wasn't working at all in my API and it's actually devistating to the progress I'm making on my application that's using the API. There's absolutely no errors being produced, the application doesn't stop, hang, or even stutter. It justs acts as if I called return and carries on with it's processing.
The in a nutshell class:
public abstract class Foo {
private static Foo singleton;
public Foo() {
singleton = this;
}
public static Foo getSingleton() {
return singleton;
}
public abstract int bar();
}
in which I have another class that inherits from this like so:
public class Bar extends Foo {
public Bar(...) {
super...
}
#Override
public int bar() {
return 5;
}
}
Now, the class "Bar" isn't in the same project as the "Foo" class, as the "Foo" class is part of an API (.jar) that is added as a dependency; However inside the .jar I have some code that needs to reference the value set by the overriden class over bar()
The code that I'm using that currently upsets my girlfriend is below:
int foo = Foo.getSingleton().bar(); // This should return the value of 5 set earlier
Which does not set the value of foo, and in-fact doesn't even print out to the console if I add a System.out.println after it. It literally just feels like it return's

This constructor
private static Foo singleton;
public Foo() {
singleton = this;
}
which initializes the static singleton field will only be invoked if you create a new instance of a subtype of Foo, ie. Bar.
You haven't showed a new instance creation expression involving Bar, so I assume there isn't one.
As such
int foo = Foo.getSingleton().bar(); // This should return the value of 5 set earlier
can only terminate with a NullPointerException when trying to invoke bar() on the null returned by getSingleton().
If you aren't seeing the NPE, then you must be catching it and ignoring it.

Your singleton is not correctly implemented. Foo.getSingleton() will return singleton which is null at that point. The static variable is only initialized in the constructor which is never called in your example. You'll have to initialize singleton in a static context, e.g. inside your getSingleton() method with a null check:
public static Foo getSingleton() {
if(singleton == null) {
singleton = new Foo();
}
return singleton;
}
EDIT
As MihaiC correctly stated in the comments, this wouldn't work since Foo is abstract. I did miss that little detail. Considering this it really doesn't make sense to have a singleton of an abstract class, unless you try to somehow initialize it with a Bar instance. The design still feels strange to me. Still leave my answer above for now for the general concept.

Related

SIngleton object initialization and dependency injection

I usually create singleton classes using singleton holder pattern like this:
public class Foo {
private static final class SingletonHolder {
private static final Foo INSTANCE = new Foo();
}
private Foo(){}
public static final Foo getInstance(){
return SingletonHolder.INSTANCE;
}
}
Everything ok. But, what about if I need inject one dependency to initialize the singleton object?
In that case, I add one method initialize that receives the dependency and must be called just one time:
public class Foo {
private static final class SingletonHolder {
private static final Foo INSTANCE = new Foo();
}
private Foo(){}
public static final void initialize(Dependency d) {
SingletonHolder.INSTANCE.setDependency(d);
}
public static final Foo getInstance(){
return SingletonHolder.INSTANCE;
}
}
Am I in the right way? Is there another solution? I know that it depends on the program, my logic and so on... but how generally should be solved this problem?
I think you are overcomplicating it. In a few places I worked (including my current one) we don't try to enforce singletons. All the wiring for the actual application is done in one place, so if you searched for usages of constructor you should find one in src and probably multiple in test. See the code below.
A few disadvantages of your approach:
you lose immutability, Foo's dependency can change
both setDependency and initialize methods are test code in production
your constructor doesn't create a valid object, a second half of constructor is in initialize method which you have to remember to call after calling constructor
SingletonHolder is a boiler plate code, I am not sure why don't you just declare public static final Foo instance field instead?
it is still possible to create multiple instances of Foo using reflection API and object serialisation mechanisms
public class Foo {
private final Dependency dependency;
public Foo(Dependency dependency) {
this.dependency = dependency;
}
// ...
}
public class Dependency {
// ...
}
The problem with this approach is that the initialize method can be invoked more than once, and there is no indication in your code that setting the dependency is being handled with thread safety.
If you're fine with that, then your lazy initialization idiom is fine.
Otherwise, you could throw an IllegalStateException or otherwise silently do nothing when the dependency is being set more than once within your singleton instance.
Edit
As Andy Thomas says, you also aren't checking whether the dependency is set before getInstance is invoked, or at least your code doesn't display it.

Why this Singleton Pattern doesn't result into StackOverflowError?

I've recently come across this kind of code somewhere.
package com.singleton;
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return singleton;
}
public static void main(String[] args) {
Singleton obj = Singleton.getInstance();
System.out.println("Done creating Singleton");
}
}
Now, problem in this might not be apparent at first glance. Atleast not to me :p
so, adding this function makes the problem clear enough
public void print() {
System.out.println("Printing inside Singleton Variable");
singleton.print();
}
public static void main(String[] args) {
Singleton obj = Singleton.getInstance();
obj.print();
System.out.println("Done creating Singleton");
}
Now, running the program would result into a StackOVerflowError
My question is, There already was this one object inside another kind of pattern in the code. so why it didn't resulted into a StackOverflowError in first case.(i.e. before addition of print function and calling it in main class.)
The source of your confusion is that you think the singleton definition is recursive. It isn't, actually.
private static Singleton singleton = new Singleton();
This is a definition of a static field. This means that this field does not exist inside any instance of Singleton. It is associated with the Singleton class, and initialize at the loading of the class.
If this was not a static call, then you would be right. Creating an instance would create a new field which would create a new instance which would create a new field.
But for a static field, initialization is done only once, at the loading of the class. It then calls the constructor of the class, and that's it - no more creations of Singleton, no more initialization, and no self-reference.
So this example will cause a StackOverflowError:
public class Test
{
public Test test = new Test();
public Test() {
}
public static void main (String[] args ) {
System.out.println( new Test() );
}
}
And this is because the field test is not static but an instance variable, and thus its initialization is done when a new instance is created, and in itself create a new instance and so on.
Change the definition of test to static and the error will go away.
Two different scenarios here. Singleton's singleton will be initialized just once when Singleton class itself would get loaded. Hence when you will call getInstance on singleton, it wont reinitialize itself, rather it would return the same instance again and again.
Your second example is a recursive call which call's to itself without any exit condition in it and hence leads to StackOverflowError.
You may also confusing an object relationship that is recursive:
class Foo {
private Foo foo;
Foo(){ ... }
public void setFoo( Foo foo ){
this.foo = foo;
}
}
with a dynamic recursion of a method.
There is no problem with classes like Foo if they are constructed without running into a recursion of the other kind, e.g.,
Foo(){
this.foo = new Foo(); // Ooops!
}
In your first code case, static Singleton singleton = new Singleton(); was initialized when the Singleton class loaded, every time of calling Singleton.getInstance(); just returns the variable only.
In the second code case, there exists an infinite loop call, This will cause the JVM to allocate stack frames for space indefinitely, and each stack size is limited after allocating, according to the Java Virtual Machine Specification
If the computation in a thread requires a larger Java Virtual Machine stack than
is permitted, the Java Virtual Machine throws a StackOverflowError.
so this must result in a stackoverflowerror obviously.

Referencing an enclosing instance from an inner class

This is a knowledge/curiosity question only.
After several years in Java, this has only just struck me.
class Foo {
class Bar{
Foo.this.doSomething();
}
}
When I look at Foo.this, I would assume that it's a static reference which obviously is not the case.
I know this is part of the Java spec, but exactly what is going on when you use <Class>.this?
Is it one of those "it just is" things?
I know this is part of the Java spec, but exactly what is going on when you use .this?
It just refers to a "hidden" field within Bar. It's easiest to see this by decompiling. You'll see that there's a Bar constructor taking a reference to an instance of Foo. That reference is stored in a field, and then when you use Foo.this, it just accesses that field. So assuming you'd put your Foo.this.doSomething() into a someMethod call, your code is similar to:
class Foo {
static class Bar {
private final Foo $foo;
Bar(Foo foo) {
this.$foo = foo;
}
public void someMethod() {
$foo.doSomething();
}
}
}

“Few programmers are aware of the fact that a class's constructors and methods can run prior to its initialization”

In the official Java guide “Programming with assertions” it is stated that
(last paragraph on the page)
Few programmers are aware of the fact that a class's constructors and methods can run prior to its initialization. When this happens, it is quite likely that the class's invariants have not yet been established, which can cause serious and subtle bugs.
What is meant by this? When does this happen? Is it something I have to care about in my daily use of Java?
Basically, they talk about the following situation:
public class Foo {
public static Foo INSTANCE = new Foo(); // Prints null
public static String s = "bar";
public Foo() {
System.out.println(s);
}
}
As you can see, in this case constructor runs before initializer of the static field s, i. e. prior to the full initialization of the class. It's just a simple example, but it can become more complex when multiple classes are involved.
It's not something you can often see in your everyday work, but you need to be aware of this possibility and avoid it when writing code.
As an example, consider virtual method dispatch in a constructor.
class Foo {
Foo() {
int a = bar();
b = 7;
}
private int b;
protected int baz() { assert b == 7; return b; } ;
protected abstract int bar();
}
If a subclass happened to call baz from within their implementation of bar they'd hit the assertion. The object hasn't finished construction so the Foo base class is in a bit of a state.
I think that they mean the logical initialization. For example your class A has method init() that must be called before using of any business methods. But other programmer that uses this class has not read manual and wrote new A().foo(). Probably in this case foo() cannot work correctly. In this case assertion may be useful. You can check in the beginning that init() was not called and throw assertion.
The same is with constructors. This may happen when somebody extends your class A:
class B extends A {
B() {
foo(); // init() must be called before foo!
}
}

Is it possible to access the Class object in a static method?

Consider the following Java class:
public class Foo
{
public static void doStuff()
{
// boring stuff here
}
}
Is it possible to access either the class literal Foo.class, or just the class name "Foo" from within a static method such as doStuff()? In a non-static method I would just call this.getClass(), but there is no this to use in a static method.
Edit: sorry this wasn't clear - I want to do this with explicitly using the class literal Foo.class.
Use Class<Foo> clazz = Foo.class
If you need something like:
class Foo {
static Class foo(){return the current class}
}
class Bar extends Foo {
}
and expect Bar.foo() to return Bar if called on Bar, and Foo if called on Foo - you have something wrong in your design and perhaps you need to make the methods non-static.
Unfortunately Java doesn't give you a good way to do this. You just have to reference Foo.class. This is something that is a regular annoyance for me.
For logging I solved it (the idea for the solution came from Log5j) by reading the stack, because it got really annoying to restate the class for every logger every time. Fortunately modern IDEs make it relatively painless, so that refactoring isn't really negatively impacted if you have to change the name of the class.
EDIT: Some code:
private static StackTraceElement getCallerStackTraceElement(StackTraceElement[] elements) {
for (int i = 0; i < elements.length; i++) {
if (elements[i].getClassName().equals(MyLogger.class.getName())) {
return elements[i + 1];
}
}
return null;
}
MyLogger in this case is the class where this method exists. It finds itself in the stacktrace and goes one earlier, and then extracts the class from the StackTraceElement.
The StackTraceElement[] array can be retrieved by either new Exception().getStackTrace(), or Thread.currentThread().getStackTrace(); The way this method is written it assumes the stacktrace is created on the first method call into MyLogger.
Just use Foo.class. You don't have to worry about inheritance or anything like that, since there's no object associated with a static method.
When dealing with static methods, you can think of them as libraries, where the class name becomes the library name. You tell the compiler which bar() method to run by specifying the library (class) name. Foo.bar() vs. Bar.bar().
The method itself has no parent and no instance, therefore, it can't use reflection to know what class it's part of. However, you can add a reflection method.
You can add a static method to the class that answers itself what class it's in:
public class Foo {
private static class self() {
return Foo.class;
}
public static void doStuff()
{
// Use self() to reference the Foo class
}
}
Notice that I made the self() method private because outside of the class, it makes no sense.
This works because the self() method is visible from inside the class, and inside the static method.
In contrast, PHP has a self construct to reference the current class.

Categories