Johannes Schätzl
Johannes Schätzl

Reputation: 75

Java Callable -> start thread and wait

i am new here so sorry if i put this into a wrong topic?

My question:

class TaskEol implements Callable<ArrayList<Coordinates>> {
        ArrayList<CoordinatesEolEwp> coordinates = new ArrayList<Coordinates>();

        public ArrayList<Coordinates> call() throws Exception {
            new Thread (() -> {
                indicatorDatabaseAction.setVisible(true);
                coordinates = loadCoordinatesOutOfDatabase();
                indicatorDatabaseAction.setVisible(false);
            }).start();


            return coordinates;
        }
    }

how do i wait for the Database to write the coordinates in the object before returning it?

Upvotes: 1

Views: 685

Answers (1)

Kayaman
Kayaman

Reputation: 73568

Along these lines, where myCallable is your callable but without the Thread stuff, i.e.

public ArrayList<Coordinates> call() throws Exception {
    indicatorDatabaseAction.setVisible(true);
    coordinates = loadCoordinatesOutOfDatabase();
    indicatorDatabaseAction.setVisible(false);

    return coordinates;
}

then...

ExecutorService e = Executors.newSingleThreadExecutor();
Future<ArrayList<Coordinates>> f = e.submit(myCallable);

// Note that Future.get() blocks until results are ready
ArrayList<Coordinates> coords = f.get();

Upvotes: 2

Related Questions