Robz de la Puenta
Robz de la Puenta

Reputation: 11

Why does my code create to much threads (java.lang.OutOfMemoryError: unable to create new native thread)

I try to check if an element is in a string by looking parallel through the list by splitting it:

`public class ParallelSearchComment extends RecursiveTask { private static final long serialVersionUID = 1L;

int lo; 
int hi; 
String com;
String query;
int T;

ParallelSearchComment(String c, int l, int h, String q, int Treshold){
    com=c;
    lo=l;
    hi=h;
    query=q;
    T=Treshold;
}

private int findMiddle(String text){ // Only split at whitespace chars (or some words would be missed) 

    int middle = lo + ((hi - lo)/2);
    int i= middle;                                                            
    for (i = middle; i != hi && com.charAt(middle) != ' ' && i-middle <= query.length()+1; i++){

    }  
    middle = i;
    return middle;
}

@Override
protected Boolean compute() {
    int middle = findMiddle(com);
    if (hi - lo < T || hi-middle <= query.length()) {//hi-middle <= query.length()
        return com.substring(lo, hi).contains(query);
    } else {

        ParallelSearchComment left = new ParallelSearchComment(com, lo, middle, query, T);
        ParallelSearchComment right = new ParallelSearchComment(com, middle, hi, query, T);

        left.fork();
        boolean resRight = right.compute();
        boolean resLeft = left.join();

        return resRight || resLeft;
    }

}

static boolean ParallelSearchComment(String c, String query, int T,int p) {
    final ForkJoinPool fjPool = new ForkJoinPool(p);
    ParallelSearchComment t = new ParallelSearchComment(c, 0, c.length(), query, T);
    return fjPool.invoke(t);
}

`

Upvotes: 1

Views: 155

Answers (2)

Timir
Timir

Reputation: 1425

Since your snippet doesn't show how static boolean ParallelSearchComment is being invoked, I'll assume that it's being used to initialize your search. Also, I'll assume that you've triggered the search only once from your main.

With that, it's quite likely that the parallelism value, or p, that you're passing in is higher than your current JVM heap can handle. See what happens when you reduce it to 5 or 10.

Upvotes: 0

Stephen C
Stephen C

Reputation: 718708

The problem is that you are creating a new ForkJoinPool instance each time you call ParallelSearchComment. Instead you should create one ForkJoinPool and use throughout the application.

Upvotes: 1

Related Questions