When you’re working with multi-threaded programming in Java — such as when working with Thread, Runnable, SwingUtilities.invokeLater, Akka, futures, or Observable in RxJava — you may need to get the name of the current thread as a way to debug your code. Here’s how you get the name of the current thread in Java:
I haven’t tried it yet, but as a note to self, Scala 2.12.5 introduced a new
-Ybackend-parallelism N compiler flag with which “the backend can now run in parallel on N threads.”
As a quick example of how to use a
Thread with a basic
Handler in an Android application, the following code creates a view where the text in the
TextView is updated to show the current date and time when the
Button is tapped.
Java source code
First, here’s the Java source code for a file class named
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:
This is a good article that shows several different ways to handle background tasks in Android, including
- Java threads
- Android HandlerThread
- Java Timer
I was just working with an example of how to use Android’s new Room Persistence Library, and the example I was working with ran some of its code on the main Android thread, also known as its “UI thread.” I knew this was bad, but I wanted to start with someone’s example, and then figure out a good way to get the Room method calls to run on a background thread, such as using an
AsyncTask. (The Android docs don’t specify a “best practice” for this atm.)
This image comes from a reactivesystems.eu article titled, Things I wish I knew when I started building reactive systems.
Martin Odersky: “There is no silver bullet for all concurrency issues.” From the book, Learning Concurrent Programming in Scala.