Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>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 <code>exec</code> or <code>exec[0]</code> is non-null there is also no guarantee that the <code>ScheduledFuture</code> object 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 your <code>do stuff here</code> code a month from now and it starts to fail.</p> <p>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 <code>AtomicReference</code>:</p> <pre><code>final AtomicReference&lt;ScheduledFuture&gt; futureReference = new AtomicReference&lt;ScheduledFuture&gt;(); ScheduledFuture exec = executor.scheduleAtFixedRate( new Runnable() { int totalSends = 0; public void run() { //do stuff here if (++totalSends &gt;= repetitions) { // we need to wait for the future to be initialized while (futureReference.get() == null) { try { Thread.sleep(1); } catch (InterruptedException e) { Thread.currentThread.().interrupt(); } } futureReference.get().cancel(true); } } }, 0, delay, TimeUnit.MILLISECONDS); futureReference.set(exec); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload