C
cppaddict
I have a class whose behaviour changes with state. The current
behaviour is determined by a Strategy object. Often, after a given
Strategy executes, it needs to change the object's active strategy, so
that on the next call a new Strategy will be called. The sample class
below illustrates this concept, compiles, and works.
public class Test {
public static void main (String[] args) {
Test t = new Test();
t.doIt();
t.doIt();
t.doIt();
}
private Strategy mStrategy = new Strategy1();
public void doIt() {
mStrategy.doIt();
}
interface Strategy {
public void doIt();
}
private class Strategy1 implements Strategy {
public void doIt() {
mStrategy = new Strategy2();
//Can this object be garbage collected here???
System.out.println("Executing Strategy1");
}
}
private class Strategy2 implements Strategy {
public void doIt() {
mStrategy = new Strategy1();
System.out.println("Executing Strategy2");
}
}
}
But question is: Is it safe? It seems that, where the code is marked
with a comment, the currently executing strategy is no longer referred
to by mStrategy, and so could possibly be garbage collected?
Or is this perfectly legal, because the collector will not collect an
object which is still executing code?
Thanks for any explanation,
John
behaviour is determined by a Strategy object. Often, after a given
Strategy executes, it needs to change the object's active strategy, so
that on the next call a new Strategy will be called. The sample class
below illustrates this concept, compiles, and works.
public class Test {
public static void main (String[] args) {
Test t = new Test();
t.doIt();
t.doIt();
t.doIt();
}
private Strategy mStrategy = new Strategy1();
public void doIt() {
mStrategy.doIt();
}
interface Strategy {
public void doIt();
}
private class Strategy1 implements Strategy {
public void doIt() {
mStrategy = new Strategy2();
//Can this object be garbage collected here???
System.out.println("Executing Strategy1");
}
}
private class Strategy2 implements Strategy {
public void doIt() {
mStrategy = new Strategy1();
System.out.println("Executing Strategy2");
}
}
}
But question is: Is it safe? It seems that, where the code is marked
with a comment, the currently executing strategy is no longer referred
to by mStrategy, and so could possibly be garbage collected?
Or is this perfectly legal, because the collector will not collect an
object which is still executing code?
Thanks for any explanation,
John