BarneyL. BarStin BarneyL. BarStin - 6 months ago 11
Java Question

Why my cyclicBarrier is null?

Im learnign about ciclycbarrier and im trying to create a little app. The constructor of my app is the follow:

public FileDownloader(String line, int maxDownload){
this.position = 0;
this.line = line;
this.maxDownload = maxDownload;
this.urls = new ArrayList<String>();
this.ths = new ArrayList<Thread>();
this.exm = new Semaphore(1);
this.GenerateURLS();
final CyclicBarrier cb = new CyclicBarrier(this.maxDownload, new Runnable(){
@Override
public void run(){


System.out.println("All download are finished");
//Mergear cuando se termina
//Borrar cuando se termina
}

});

for(int i=0; i<this.maxDownload;i++){
ths.add(new Thread(new Task(this.cb),"Hilo"+i));
}
for(Thread th: ths){
th.start();
}

}


In the constructor i create my Cyclicbarrier, setting a maxDownload number and a new Runnable. After That, y create all my thread setting a Task(setting the cyclicbarrier. The tasks implements Runnable). The code of my task is the follow:

class Task implements Runnable{
private CyclicBarrier barrier;
public static int position;
public Task(CyclicBarrier cb){
this.barrier = cb;

}

public void run(){
try {

FileDownloader.DownloadManager();
this.barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.getStackTrace());
}
}
}


But the problem is when the method DownloadFile(Inside Run of my task) ends, and its time to do cb.await, i have the next error:

Exception in thread "Hilo1" java.lang.NullPointerException
at Prac2.Task.run(FileDownloader.java:23)
at java.lang.Thread.run(Thread.java:745)


and debugging i can see that the cyclicbarrier(barrier) in my task is always null, but the cb not.

what can be the problem?enter image description here

Answer

Look closely on your code.

You create local variable cb.

 final CyclicBarrier cb = new CyclicBarrier(this.maxDownload, new Runnable(){
    @Override
    public void run(){
        System.out.println("All download are finished");
        //Mergear cuando se termina
        //Borrar cuando se termina
    }

});

But here you access class-level variable.

for(int i=0; i<this.maxDownload;i++){
    ths.add(new Thread(new Task(this.cb),"Hilo"+i));
}

I mean following:

this.cb

Be attentive.

Comments