Androider
Androider

Reputation: 21345

Java Threading Error IllegalThreadState thread already started

Whenever I start my thread I always do this check. I did not find anywhere that I called start on thread without doing the check below

if (!myThread.isAlive())
    myThread.start();

Nevertheless, I end up with IllegalThreadStateException : Thread already started. This actually crashes my app (android). So is there some other check I need to do before starting up a thread?

Upvotes: 7

Views: 9518

Answers (3)

Johanna
Johanna

Reputation: 5303

I just had a similar case here, that's why I give a late answer.

The problem is, your solution with Thread.isAlive() and Thread.start() is not multithread-safe. It can happen a first thread calls your code, executes isAlive() and somewhere inside Thread.start(), after the new thread was started and before it state is changed, a task switch occurs and a second caller executes isAlive() when it is still false thus making start()being called twice. To make it worse somewhere inside start()it seems a task switch is forced and thus this problem appears quite often.

Solution: Override start() to make it multithread-safe, for example

private final AtomicBoolean started = new AtomicBoolean(false);
/* (non-Javadoc)
 * @see java.lang.Thread#start()
 */
@Override
public synchronized void start() {
    if (!started.getAndSet(true)) {
        super.start();
    }
}

Then your problem won't appear any more, even if start() accidentally is called twice.

Upvotes: 0

MByD
MByD

Reputation: 137382

You should check if the thread has already started using getState() and start it only if its state is NEW, otherwise create new thread (if needed).

Upvotes: 11

Dariusz Jędrzejczyk
Dariusz Jędrzejczyk

Reputation: 911

Do you create a new instance for myThread reference using new? You can only perform myThread.start() once on a single instance.

Checking if it is alive is not the right way. Create a new instance.

Upvotes: 3

Related Questions