Shiva Kumar
Shiva Kumar

Reputation: 3161

How do I test the completion of threads created under my testmethod in JUnit

I have a method createThreads which spawns few new threads. Each of the newly created thread does some work. If I invoke the method `createThreads' in junit, how can i ensure that all the newly spawned threads have also completed successfully.

I am currently calling as below

@Test
public void test() {
    createThreads();  // Does not wait until the newly created threads also finish.    
}


public void createThreads()
{
ExecutorService executorService = Executors
        .newFixedThreadPool(numThreads);
for (int i = 0; i < numThreads; i++) {
    executorService.execute(new Runnable() {
        @Override
        public void run() {
            try {
               Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("I have completed execution " + Thread.currentThread().getName());
        }
    });
}

Note that I cannot modify createThreads

Upvotes: 1

Views: 128

Answers (2)

gjambet
gjambet

Reputation: 369

try running this, you'll see that they are quite easy to identify :

public static void main(String[] args) {

    int nb = 3;
    ExecutorService executorService = Executors.newFixedThreadPool(nb);
    for (int i = 0; i < nb; i++) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("I have completed execution " + Thread.currentThread().getName());
            }
        });

    }


    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    for (Thread t : threadSet) {
        System.out.println(t.getName());
    }

}

sorry for a 2nd answer not possible to add such a long code in comment

Upvotes: 0

gjambet
gjambet

Reputation: 369

a bit odd but..

you can probably get all the runing threads

through Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); then filter it to identify the thread from the executor service. then do a .join() on each of those threads.

as i said, a bit odd but it should fit your needs ...

Upvotes: 2

Related Questions