Android Room, database I/O, and Java 8 threads

I just started working with the Android Room database persistence library, and since you’re not supposed to run things like database queries on the main thread (the UI thread), I was looking at other ways to run them.

In general, you probably won’t want to run database queries using a Thread, but just to see how Room works, I wrote this Java Thread code, and confirmed that it works as expected:

// works (pre-java8)
Thread t = new Thread() {
    public void run() {
        mAppDatabase.userDao().insert(u);
    }
};
t.start();

Since that code runs in a separate thread, it runs fine even if I enable Android’s StrictMode.

Java 8 Thread syntax

Then I thought, “Hey, if I use the Android Studio 3 Canary Preview, I can use Android’s Java 8 features,” and when I did that I was able to use this Java 8 Thread syntax for the same purpose:

// works (java8)
new Thread(() -> {
    mAppDatabase.userDao().insert(u);
}).start();

That also works, and it’s much easier to read than the old Java Thread syntax.

As a quick summary, if you want to use a Java 8 Thread with Android, I hope that last example is helpful. I don’t often interact with a database without calling back to update the UI, but when I’m writing a little test app, or testing new features like the Android Room persistence library, this is a simple approach to keep database I/O code off the main thread.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.