Reputation: 170
I had a look at JAVA and tried to play around with an ExecutorService. Unfortunately my executor doesn’t start my runnable objects. I’m trying to get some information from different XML files, which are stored in the files list.
FileFinder fileFinder = new FileFinder(path);
List<File>files = fileFinder.getFiles();
ExecutorService threadPool = Executors.newFixedThreadPool(configReader.getThreadcount(), new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new EinbucherThread();
}
});
for(File file : files)
{
System.out.println("Started working");
USEinbucher einbucher = new USEinbucher(file, verbindung);
threadPool.execute(einbucher);
}
threadPool.shutdown();
try {
while(!threadPool.awaitTermination(1, TimeUnit.SECONDS)) {
i++;
System.out.println("waiting "+i );
;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
I thought I could increase the performance by putting the unmarshaller in my threads. So I don’t need to create an unmarshaller for each file, but just once per thread (as far as I understood the API each thread can be used multiple times).
public class EinbucherThread extends Thread {
private Unmarshaller um;
public EinbucherThread() {
try {
JAXBContext jb = JAXBContext.newInstance("klassen");
um = jb.createUnmarshaller();
System.out.println("Thread was created");
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Unmarshaller getUm() {
return um;
}
Unfortunately it seems, as if the run method of my runnable class is never reached.
public class USEinbucher implements Runnable {
private File lieferung;
private Verbindung verbindung;
public USEinbucher(File lieferung, Verbindung verbindung) {
this.lieferung=lieferung;
this.verbindung=verbindung;
}
@Override
public void run()
{
System.out.println("Started to work");
einbuchen();
}
I inserted some println for debugging. With three files and a threadcount of two my output looks like:
Started working
Thread was created
Started working
Thread was created
Started working
Thread was created
waiting 1
waiting 2
waiting 3…
Any explanation is appreciated.
Upvotes: 0
Views: 1367
Reputation: 8348
The ThreadFactory.newThread should return a Thread
that is responsible for running the parameter Runnable
object. Consider passing the Runnable
parameter to your Thread object. For example:
@Override
public Thread newThread(Runnable r) {
return new EinbucherThread(r);
}
//in the constructor of EinbucherThread
public EinbucherThread (Runnable r){
super(r);
}
Upvotes: 2