Dave Carpeneto
Dave Carpeneto

Reputation: 1080

Inline runnable with constructor?

I'm looking to use a thread to process something in the background. Since this code isn't used anywhere else & is not complex I'd like to use an inline function. However the function needs a copy of an attribute at the time the thread was created i.e.: I'd like it if the output from the following example 'true' instead of 'false'

public class InlineThreadTest {
    boolean value;

    public static void main(String[] args) {
        new InlineThreadTest();
    }   

    InlineThreadTest() {    
        value = true;
         java.util.concurrent.Executors.newSingleThreadExecutor().execute(new Runnable() {
            @Override 
            public void run() {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {}         
                System.out.println(value);
            }
        });
        value = false;
    }
}

... I can do what I'm looking to do by creating a separate class that implements Runnable, but having this inline seems like something that might be good.

I had a look @ https://stackoverflow.com/a/362443/64696 , but cannot figure out how to mold this to my use case.

Upvotes: 0

Views: 1121

Answers (1)

user2670200
user2670200

Reputation:

Runnable implementation is a thread and thread won't return any value. The ExecutorService.execute method just runs the thread and you have no way to get the state of the thread whether it was executed or not. If you want to check for the task (not thread) executed by ExecutorService you should use Callable and work with sumbit(). Your modified example:

public class InlineThreadTest {
boolean value;

public static void main(String[] args) {
    new InlineThreadTest();
}   

InlineThreadTest() {  
    value = true;
    java.util.concurrent.Future<Boolean> f =
     java.util.concurrent.Executors.newSingleThreadExecutor().submit(new Callable<Boolean>() {
         public Boolean call() {
           System.out.println(value);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {}
            value = false;
            return value;
        }
    });
    try {
      System.out.println(f.get()+" or value="+value);
    } catch (Exception ex) { }
}

}

You'll get 2 lines

true
false or value=false

Upvotes: 1

Related Questions