2

I have a method that I only want to have called when not on the main thread (does heavy work) and if it is called from the main thread I would throw a runtime exception, similar to what happens when you try to do a network call on the main thread and you get a NetworkOnMainThreadException

I have not found anything on this issue so is there a way to do it?

tyczj
  • 71,600
  • 54
  • 194
  • 296
  • 2
    @Akshay did you even read my question!? this has nothing to do with my question – tyczj Aug 13 '14 at 15:54
  • 1
    @tyczj Sorry, I was reading too quickly and misunderstood, my apologies. I've added an answer below that hopefully addresses your question more properly. – Akshay Aug 13 '14 at 15:58
  • @NiekHaarman I guess I should have searched "UI thread" instead of "main thread" – tyczj Aug 13 '14 at 15:59
  • Looper.myLooper() == Looper.getMainLooper() – pskink Aug 13 '14 at 16:04

2 Answers2

0

You can compare the current thread with the one of the main Looper

if (Thread.currentThread() == Looper.getMainLooper().getThread())
    throw new IllegalStateException();
Antoine Marques
  • 1,379
  • 1
  • 8
  • 16
0

You can use Thread.currentThread() to get a reference to the current thread. If you remember the the main thread on start you can verify that the method is being called from the correct one.

For instance, you could write:

// At the start of the main thread, keep a reference

Thread mainThread;

public void mainThreadMethod()
{
    mainThread = Thread.currentThread();
    // ...
}

// In the relevant method, check the thread you're on

public void myMethod()
{
    if(Thread.currentThread().equals(mainThread))
    {
        throw new RuntimeException("Method called from main thread");
    }
    // ...
}
Akshay
  • 814
  • 6
  • 19
  • Why bother with the ID? Why not just compare the actual Thread object? – Solomon Slow Aug 13 '14 at 16:27
  • @jameslarge I've always thought IDs are easier to store. I guess you could compare the actual `Thread`s if you really wanted to. – Akshay Aug 13 '14 at 16:31
  • I would really want to compare the actual Thread because it's fewer method calls. As for storing: On a 64-bit platform, the size of a Thread reference will be the same as the size of a long. On a 32-bit platform, the Thread reference might actually be smaller. – Solomon Slow Aug 13 '14 at 16:33
  • @jameslarge Interesting, I didn't actually know that. I'll update my answer accordingly. – Akshay Aug 13 '14 at 16:35