public final void sendAdvertisement(final Advertisement advertisment, int delay, final int repetitions){
final ScheduledFuture exec = executor.scheduleAtFixedRate( //<< initialized on this line
new Runnable(){
int totalSends = 0;
public void run(){
//do stuff here
if(++totalSends >= repetitions) exec.cancel(true); //<< here is says exec might not be initialized
}
},
0, delay, TimeUnit.MILLISECONDS);
}
If this isn’t possible, could you suggest a better way to do this? I couldn’t find a method for it in ScheduledThreadPoolExecutor. basically what I’m trying to do is make this code be run 3 times then cancel the “timer.” I could probably use Swing Timer, but I don’t want to since its used for other stuff.
It says in the comments, but this is the error:
%PATH%Discovery.java:148: variable exec might not have been initialized
if(++totalSends >= repetitions) exec.cancel(true);
Your code may work from the standpoint of removing the compiler warning but the whole point of the warning is pointing out that you may be accessing a variable that has not been assigned yet. Even if
execorexec[0]is non-null there is also no guarantee that theScheduledFutureobject has even been properly initialized — yes even though the inner thread may be running. This is very dangerous and might work for a while but then fail dramatically in production, when you move to an architecture with more cores, or under different load circumstances. It also may work but then you change yourdo stuff herecode a month from now and it starts to fail.I see a couple of ways that you can accomplish this in a better manner. They are more complicated but also more safe and consistent with Java. The first that comes to mind is by using the
AtomicReference: