java - Threaded quicksort -


hello i've never tried using threads before, first attempt doesn't stop, normal verion works. if remove awaittermination looks works need method finish when it's sorted out(pun intended xd). can tell me did wrong? thank you.

public class sorting {    private sorting() {};    private static random r = new random();   private static int cores = runtime.getruntime().availableprocessors();   private static executorservice executor = executors.newfixedthreadpool(cores);    public static void qsortp(int[] a) {     qsortparallelo(a, 0, a.length - 1);   }    private static void qsortparallelo(int[] a, int first, int last) {     while (first < last) {       int p = first + r.nextint(last - first + 1);       int px = a[p];       int = first, j = last;       {         while (a[i] < px)           i++;         while (a[j] > px)           j--;         if (i <= j) {           scambia(a, i++, j--);         }       } while (i <= j);       executor.submit(new qsortthread(a, first, j));       first = i;     }     try {       executor.awaittermination(1, timeunit.days);     } catch (interruptedexception e) {       e.printstacktrace();     }   }    private static void scambia(int[] a, int x, int y) {     int temp = a[x];     a[x] = a[y];     a[y] = temp;   }    public static class qsortthread implements runnable {     final int a[], first, last;      public qsortthread(int[] a, int first, int last) {       this.a = a;       this.first = first;       this.last = last;     }      public void run() {       qsortparallelo(a, first, last);     }   } } 

instead of waiting termination of entire executor service (which isn't want @ all), should save futures returned executor.submit() , wait until they're done (by calling 'get()` on them example).

and though it's tempting in qsortparallelo() method, lead deadlock exhaustion of thread pool: parent tasks hog worker threads waiting child tasks complete, child tasks never scheduled run because there no available worker threads.

so have collect future objects concurrent collection first, return result qsortp() , wait there futures finish.

or use forkjoinpool, designed kind of task , donkey work you. recursively submitting tasks executor application code not idea, it's easy wrong.


as aside, reason code deadlocked is every worker thread stuck in executor.awaittermination(), thereby preventing termination of executor service.

in general, 2 useful tools designing , debugging multi-threaded applications are:

  1. a thread dump. can generate jstack, visualvm or other tool, it's invaluable in deadlock situations, gives accurate image of what's (not) going on threads.
  2. a pen, piece of paper , drawing old fashioned swimlane chart.

Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -