Using Java Stream API in already multi-threaded environment -
my application has own thread pool(mythreadpool) , assigning 1 of threads(producer) read file via java stream api. in runtime stream lost somewhere , never reaches print method. when run stream in single threaded environment works. happen because java stream api uses own thread pool underneath or conceptually wrong?
public class processor { public void process() { executorservice mythreadpool = executors.newfixedthreadpool(3); mythreadpool.execute(new producer()); } private class producer implements runnable{ @override public void run() { try (stream<string> lines = files.lines(paths.get("path"))) { system.out.println(lines.count()); } catch (ioexception e) { e.printstacktrace(); } } } }
i don't know have happen. can give advice (maybe program exited , producer not terminated). copy code , see wrong of code.
public class processor { public void process() { executorservice mythreadpool = executors.newfixedthreadpool(3); try { mythreadpool.execute(new producer()); thread.currentthread().join(); } catch (exception ex) { ex.printstacktrace(); } } private class producer implements runnable { @override public void run() { try (stream<string> lines = files.lines(paths.get("path"))) { system.out.println(lines.count()); } catch (ioexception e) { e.printstacktrace(); } } } }
or
public class processor { public void process() { executorservice mythreadpool = executors.newfixedthreadpool(3); try { mythreadpool.submit(() -> { new producer().run(); return null; }).get(); } catch (exception ex) { ex.printstacktrace(); } } private class producer implements runnable { @override public void run() { try (stream<string> lines = files.lines(paths.get("path"))) { system.out.println(lines.count()); } catch (ioexception e) { e.printstacktrace(); } } } }
Comments
Post a Comment