Reputation: 5534
So this code was given in an exam and the question was what's wrong with it. It's meant to create new objects of type SomeClass
but only if they were not created earlier.
class Foo {
private SomeClass x = null;
public synchronized SomeClass getX() {
if (x == null)
x = new SomeClass();
return x;
}
}
My guess is that x
and getX
should be declared static since otherwise there may be multiple copies of x
. Is that correct? if so is that the only problem in the code?
Upvotes: 0
Views: 78
Reputation: 15641
You are trying to build a singleton factory method:
public class Foo {
private static SomeClass x = null;
public static synchronized SomeClass getSomeClass() {
if (x == null)
x = new SomeClass();
return x;
}
}
Note that if you really need this, you should also make SomeClass an inner class of Foo, and make the constructor of SomeClass private.
Upvotes: 1