Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are basically two ways I know of to get around this. Unfortunately neither of them is especially nice regarding the resulting code quality, so I'm not sure if I can recommend them. </p> <p>The first solution would be to make exec a final one-element array. Then you can assign exec[0] = something after declaration even tho the array itself is final. A variation of this is to use/create some reference class (since you can alter attributes of final references, but not the references themselves). The following is a simple example, but keep in mind that it does not take any concurrency issues into consideration (see further down):</p> <pre><code> final ScheduledFuture[] exec = new ScheduledFixture[1]; exec[0] = executor.scheduleAtFixedRate( //&lt;&lt; initialized on this line new Runnable(){ int totalSends = 0; public void run(){ //do stuff here if(++totalSends &gt;= repetitions) exec[0].cancel(true); //&lt;&lt; here is says exec might not be initialized } }, 0, delay, TimeUnit.MILLISECONDS); </code></pre> <p>Alternatively you could move exec out of the local scope of the method and make it a class attribute instead. </p> <p>I must however warn you that, especially with the initial delay of zero, there is a real possibility of the code inside the runnable being executed before the scheduleAtFixedRate method returns, in which case exec[0] will still be null. Also, you should use synchronization to ensure that the value of exec[0] as set by the main thread will be available to the thread responsible for executing the runnable. </p> <p>Both of the above solutions should work, but I don't think that either of them is especially nice. </p>
 

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