Question

How would i pass an argument to the ScheduledThreadPoolExecutor?

I have the following code. You will notice that i have declared a variable 'num' and it is passed as an argument to exampleFunction(). exampleFunction contains a ScheduledThreadPoolExecutor. I want to be able to use the variable 'num' inside public void run(). Is there any way i can do that?

     class Test {
     ...
     int num;
     exampleFunction(num);
     ...

     public void exampleFunction(num) {
         ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
         exec.schedule(new Runnable() {
             public void run() {
                 ...do something here...
                 ...something with 'num' here...
                 ...i get an error when i try to use 'num' here
             }
         }, 10, TimeUnit.SECONDS);
     }

}
Was it helpful?

Solution

Did you try changing exampleFunction(num) as exampleFunction(final int num)? Since run method is in an inner class all external bindings need to be final.

public void exampleFunction(final int num) { // final int here
     ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
     exec.schedule(new Runnable() {
         public void run() {
             ...do something here...
             ...something with 'num' here...
             ...i get an error when i try to use 'num' here
         }
     }, 10, TimeUnit.SECONDS);
 }

OTHER TIPS

Either make num final or static (or accessible from a static method), or else create your own Runnable.

class MyRunnable implements Runnable {
    int num;

    public MyRunnable(int num) {
        this.num = num;
    }

    public void run() { ... }
}

declare you variable num final and you will be able to use it inside the Run() method.

Write this instead

final int num;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top