0

I have the following section of code for a small brute-forcer. I've been trying to learn multi-threading and I have executors that will not stop.

private void generateThreads(int cores){
    if (cores > Runtime.getRuntime().availableProcessors() || cores <= 0)
        cores = Runtime.getRuntime().availableProcessors();

    ArrayList<Future<?>> tasks = new ArrayList<Future<?>>(cores);
    ExecutorService executor = Executors.newFixedThreadPool(cores);
    final long step = 2000;

    for (long i = 0; i < Long.MAX_VALUE; i += step){
        while(tasks.size() > cores) {
            for(int w = 0; w < tasks.size();w++){
                if(tasks.get(w).isDone()){
                    tasks.remove(w);
                    break;
                }
            }

            try{
                Thread.sleep(0);
            }

            catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        {
            if (passwordFound == false){
                tasks.add(executor.submit(new Runnable(){

                    public void run(){
                        String attempt;
                        while(true){
                            try {

                                Thread.sleep(0);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            attempt = bf.toString();
                            bf.increment();
                            if (passwordCrack(attempt)){
                                crackedPassword.append(attempt);
                                passwordFound = true;
                                break;
                            }

                        }
                    }
                }));
            }
            else
                break;
        }
    }
    executor.shutdownNow();
}

I thought that the Thread.sleep(0) would give the thread the ability to catch the InterruptedException, but my threads continue to go forever. What can I do to make sure that once a password is found, the threads stop correctly?

tophersmith116
  • 432
  • 1
  • 5
  • 19

2 Answers2

2

You have to also check passwordFound variable:

// inside your run() method
while(!Thread.currentThread().isInterrupted() && !passwordFound) {
  ...
}

Thread.sleep() is not needed, as far as I can see.

P.S. Corrected my answer a bit to make it more clear what I meant.

Andrew Logvinov
  • 21,181
  • 6
  • 52
  • 54
1

It seems you want a behavior like this:

public void run() {
  /* do something */
  while(!passwordFound) {
      /* do something */
  }      
} 

Be careful to take the lock on the variable where is stored password!

Luca Davanzo
  • 21,000
  • 15
  • 120
  • 146