user3562575
user3562575

Reputation: 9

How to return values in a new thread?

I have this piece of code and I want to return the value of, "sql" in a new thread so this query sends/fetches info from the database fast and not on the main thread. If I make a new thread and initialize a string with the sql and then return it out side of the thread, it returns null. Is there anyway I can return sql in a new thread without it being null? Thanks.

public String getCurrentG(final String username) {




            Sql2o sql2o = new Sql2o(DB_URL, USER, PASS);

            String sql = "SELECT CurrentGuild FROM Players WHERE Username='" + username + "'";

            try (Connection con = sql2o.open()) {
              return con.createQuery(sql).executeScalar(String.class);
            }


        }

Upvotes: 0

Views: 154

Answers (1)

Solomon Slow
Solomon Slow

Reputation: 27190

A thread is not a thing that can return a value. A thread is a path of execution through your code. Every program has a main thread that begins and ends somewhere in the internals of the JVM, and it can create other threads by use of Thread objects.

A thread that is created by a Thread object does nothing more or less than call the run() method of some Runnable object (possibly the Thread object itself, but that's an old-fashioned way of doing it.) Since Runnable.run() does not return a value, there is no way for a thread to "return" a value.

Of course, your run() method could store a value in some field---a field of its own, or a field in some other object that it knows about.

The "Future" interface that Dgrin91 mentioned holds a value that was stored by a thread. It's part of the java.util.concurrent package. You use a java.util.concurrent.ExecutorService to manage a pool of worker threads, and you feed it "tasks" (a.k.a., Callables) to be performed. A task can return a value. You immediately get back a Future object each time you submit a task, and when some thread from the thread pool finally completes the task; it stores the return value in the Future, and then it notifies the Future. The Future interface provides methods that you can call test whether the task has been completed, to wait for the task to be completed, and to get the value that the task returned.

Upvotes: 2

Related Questions