java - Method returns before executing all threads even though executor.awaitTermination is used -
i have method takes number of threads work , executes run() method each thread accordingly shown below
public static map<string, integer> execute(int thread_count) { executorservice executor = executors.newfixedthreadpool(thread_count); file folder = new file("logfiles/"); collection<file> files = fileutils.listfiles(folder, null, true); for(file file : files){ //for rach file in folder execute run() system.out.println(file.getname()); executor.submit(new runner((file.getabsolutepath()))); } executor.shutdown(); try { executor.awaittermination(1, timeunit.days); } catch (interruptedexception e) { system.out.println("exception "+ e + " in countlines.execute()"); } for(map.entry<string, integer> entry: runner.linecountmap.entryset()){ system.out.println(entry.getkey() + " : : " + entry.getvalue()); } return runner.linecountmap;// printing after threads finish executing }
and run method defined below:
public void run() { try { count = countlines(file);//get number of lines in file } catch (ioexception e) { system.out.println("exception "+ e + " in runner.run()"); } //count number of lines in each file , add map linecountmap.put(file, count); }
as have used executor.awaittermination in execute() method above, expecting linecountmap populated filesnames key , line count values. seems linecountmap being returned before threads executed.
for following files: logtest.2014-07-04.log logtest.2014-07-02.log logtest.2014-07-01.log logtest.2014-07-03.log expected output: linecountmap: /logtest.2014-07-01.log : : 4 /logtest.2014-07-02.log : : 8 /logtest.2014-07-03.log : : 2 /logtest.2014-07-04.log : : 1 actual output: linecountmap: /logtest.2014-07-01.log : : 4 /logtest.2014-07-03.log : : 2 /logtest.2014-07-04.log : : 0
here i missing content /logtest.2014-07-02.log , value /logtest.2014-07-04.log shown 0 when 1
changing linecountmap
concurrenthashmap
solved issue. oliver croisier solution discussed in comments section.
Comments
Post a Comment