FAQ Database Discussion Community


NullpointerException in Collection.sort() with multithreading

java,multithreading,nullpointerexception,executorservice
I have a class that should test my Fibonacci function using multithreading public class PerformanceTesterImpl implements PerformanceTester{ public static List<Long> executionTimesList = new ArrayList(); public static List<Runnable> tasksList = new ArrayList(); public int fib; public PerformanceTestResult performanceTestResult; @Override public PerformanceTestResult runPerformanceTest(Runnable task, int calculationCount, int threadPoolSize) { for(int i=0; i<calculationCount;...

HtmlUnit WebClient resets thread interruption status

java,multithreading,interrupt,htmlunit,executorservice
I have a bunch of parser classes that subclass a PriseParser class and implement a getAllPrices() method (called by the PriseParser.getPrices() that does some other stuff too not related to this post) in order to acquire some data from various web sites. Below is an example for such an implementation:...

Watch directory using scheduled executor instead of hard loop in Java

java,multithreading,nonblocking,executorservice,watch
In my previous question I was warking on a simple exercise that watched a directory for file changes. I took the code from this oracle docs, and it worked with no problem, except for the little unchecked cast warning I was unsure about. The next problem I have with this...

How to log an error in the console if one of the callables of the executor service encounter an error

java,multithreading,executorservice
I have a program which uses executorService to which I am passing callables. Each of which is an object of one class which implements java.util.concurrent.Callable. Then the executorService is invoked. A java.lang.NoClassDefFoundError is thrown in the middle of one of the callables in the call() method. However it is not...

Dynamic UI Progress Updates using Interface + ExecutorService Issue

java,android,executorservice
So I have a music application. I am trying to update the UI with the progress of the media player (like current time, current song, album cover) everytime the song changes. I found that using interfaces was a awesome magical way of communication between activity and fragments so I implemented...

ExecutorService - How to wait for completition of all tasks in non-blocking style

java,multithreading,web-applications,executorservice
I am using ExecutorService in Java web server application for executing some computational tasks in parallel style and then calling shutdown() with awaitTermination() to wait for all tasks to be done. Whole computation can sometimes take dozens of minutes. The thing is awaitTermination() method blocks the main thread until timeout...

Java sequential implementation is 4 times faster than parallel implementation

java,multithreading,parallel-processing,threadpool,executorservice
I created a really simple scenario where I recognized a really weird behavior which I cant understand. Under following link I created an sequential implementation: http://ideone.com/B8JYeA Basically there are several big arrays with fixed size. The algorithm iterates through them and changes the value. for(int i = 0; i <...

ExecutorService workStealingPool and cancel method

java,threadpool,executorservice
Can you think about any reason why this code doesn't work and always outputs "finished", but the second example works without any problems. I'm using latest JDK (8u45). public static class MyClass implements Runnable { @Override public void run() { try { Thread.sleep(2000); } catch (InterruptedException ex) { System.out.println("Interrupted"); return;...

Executors distribution of task per threads

java,multithreading,executorservice
I am fairly new with java executors, so this maybe an easy question. ExecutorService executorService = Executors.newFixedThreadPool(NumberOfThreads - 1); do_work(); for(int i = 1; i < NumberOfThreads; i++) { executorService.execute(new Runnable() { public void run() { do_work(); } }); } My question is: If I create a fixed thread pool...

how to know the exact time thread requires to finish

java,multithreading,executorservice,countdownlatch
I have two threads t1 and t2. Both of them make some calculations and i am tryin to block the main thread till t1 and t2 finish. I used .awaitTermination() as seen below, but the problem is, despit it is an if-statement, the .awaitTermination() goes in an infinite loop. please...

Method returns before executing all threads even though executor.awaitTermination is used

java,multithreading,concurrency,parallel-processing,executorservice
I have a method which takes number of threads to work and then executes the run() method for each thread accordingly as 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){...

Is it possible to pass Function to ExecutorService instead of callable in Java 8?

java-8,future,executorservice,callable
public class myService { @Autowired ExecutorService executor; public Result getServiceResult(Token token, Profile profile){ //validate token and profile return getResult(token, profile).get(); } private getResult (Token token, Profile profile){ Future<Result> = threadPoolExecutor.submit( () -> myManager.createAccount(token, profile)); } } This code runs fine at my current work. I am not able to able...

Why SocketTimeoutException makes my program freeze?

java,multithreading,freeze,executorservice,socket-timeout-exception
I give my program over than 600 links, stocked in an ArrayList to get the title of the webpage, using JSoup (among others). For every link (using a for loop), I create a new thread (using thread.start()) and pass the link through my program, I wait for my thread to...

Monitor thread status

java,multithreading,executorservice
So I have this very relevant thread I start when the program starts. The thread is listening to events coming from a bigger system as the main thread does other stuff. The thread should never stop working and if it does, it should be recreated and started. I think I...

Java Future.isDone returning true, even though it shouldn't, which halts program progress

java,future,executorservice
I have a SwingWorker which initiates a LinkedBlockingQueue, passes it to another method (PortalDriver, below), then reads from it in the doInBackground() method. The LinkedBlockingQueue holds futures for a custom object (and it is definitely filled correctly). As a check, the objects that I am creating (via an ExecutorService), have...

ExecutorService with number of running tasks

java,executorservice,threadpoolexecutor
I want to get the number of tasks that are submitted to an executor service and not yet finished (i.e currently running/active or queued). Executor service does not have an inbuilt method for this. ((ThreadPoolExecutor) executorService).getActiveCount() This "Returns the approximate number of threads that are actively executing tasks." Is this...

Executing one thread at a time sequentially

java,multithreading,concurrency,executorservice,java.util.concurrent
I have several threads being created in a for loop like this: for (int i = 0; i<5; i++) { new Thread() { //do stuff } } but I need to make sure that these threads execute one after the other rather than all at the same time. what is...

Java job execution multithreaded with executorservice?

java,multithreading,task,executorservice
How to i implement such a function ? I have a dynamic queue which gets filled at unknown times with runnables, which have to be executed. The ExecutorService should only start a limited amount of threads, when the maximum thread size is reached, it should stop executing more threads, until...

How to get results from the CompletableFuture

java,multithreading,threadpool,executorservice,countdownlatch
each of "CompletableFuture.runAsync" mentioned in the code below does some calculations, an i want to get the results each time i call "CompletableFuture.runAsync". or in other words, i want each of "future0,future1,future2,future3" to contain the result of each call to "CompletableFuture.runAsync" respectively how can i do that. *Update: my requirements...

ExecutorService JVM doesn't terminate [duplicate]

java,multithreading,executorservice,java.util.concurrent
This question already has an answer here: Java ServiceExecutor terminating condition 4 answers I don't understand why I have to call executorService.shutdown() explicitly to terminate executorService. If I will not call shutdown() then the JVM will not terminate on its own. What is wrong with my program or what...

Java - ScheduledExecutorService: Execute task at termination

java,executorservice,autocloseable
I use the ScheduledExecutorService to execute a task at a fixed rate. Here is the contents of my main method: RemoteSync updater = new RemoteSync(config); try { updater.initialise(); updater.startService(totalTime, TimeUnit.MINUTES); } catch (Exception e) { e.printStackTrace(); } RemoteSync implements the AutoCloseable (and Runnable) interface, so I initially used try-with-resources, like...

How to better use ExecutorService in multithreading environment?

java,multithreading,daemon,executorservice,callable
I need to make a library in which I will have synchronous and asynchronous methods in it. executeSynchronous() - waits until I have a result, returns the result. executeAsynchronous() - returns a Future immediately which can be processed after other things are done, if needed. Core Logic of my Library...

How to execute multiple queries in parallel instead of sequentially?

java,multithreading,executorservice,callable
I am querying all my 10 tables to get the user id from them and loading all the user id's into HashSet so that I can have unique user id. As of now it is sequentially. We go to one table and extract all the user_id from it and load...

Using ExecutorService to repeatedly perform a number of similar tasks in parallel

java,multithreading,concurrency,executorservice
There is Java code which when simplify loooks like this: while(someCondition) { SomeType a = CalcResult(param1); SomeType b = CalcResult(param2); SomeType c = CalcResult(param3); // Do something with a, b and c } CalcResult() is time consuming. The application runs on an SMP system. There is a push to try...

ExecutorService that scales threads then queues tasks

java,multithreading,executorservice
Is there an ExecutorService implementation that behaves like a thread pool with the following characteristics? There are always at least X active threads. If a task is submitted and all active threads are busy, a new thread is started, up to Y threads. If a task is submitted and...

Difference between ForkJoinPool and normal ExecutionService?

java,executorservice,fork-join
I read a great article about the fork-join framework in Java 7, and the idea is that, with ForkJoinPool and ForkJoinTask, the threads in the pool can get the sub tasks from other tasks, so it's able to use less threads to handle more tasks. Then I tried to use...

Parallel in Java 7 with a result, using non-final variables

java,parallel-processing,executorservice
I have a something like: int [] array1 = new int[20]; int [] array2 = new int[20]; int total= 0; Random generator = new Random(); for(int i = 0; i < 10000; i++){ int tmp = generator.nextInt(20); boolean win = custom_function(...); array1[tmp]++; array2[tmp]++ total++; } // do something with the...

Is Thread to be favoured over Executor here?

java,concurrency,executorservice
As far as I understand Executors help handling the execution of runnables. E.g. I would choose using an executor when I have several worker threads that do their job and then terminate. The executor would handle the creation and the termination of the Threads needed to execute the worker runnables....

Java multithreading performance

java,multithreading,executorservice
So I've been playing around with threads in Java and I made a test. I made a program that makes around 10^9 multiplyings and then prints the milliseconds that were needed. The program has 2 modes one of them does not print anything but just the milliseconds needed. The other...

Is it possible to have a set of thread pools that share threads from a large thread pool instead of creating new thread?

java,multithreading,concurrency,threadpool,executorservice
Is it possible to have a set of thread pools that share threads from a large thread pool instead of creating new thread? In our RESTful API application, a request may involve several parallel tasks. To improve the performance, we want to execute parallel tasks in a thread pool which...

How to get the exception from a cancelled+interrupted callable submitted to an executor?

java,multithreading,concurrency,executorservice
Consider the following code: ExecutorService executor = Executors.newSingleThreadExecutor(); final CountDownLatch taskStarted = new CountDownLatch(1); Future<String> future = executor.submit( new Callable<String>() { @Override public synchronized String call() throws Exception { try { taskStarted.countDown(); this.wait( 60000 ); return "foo"; } catch( Exception iWantToGetThisExceptionOutside ) { iWantToGetThisExceptionOutside.printStackTrace(); throw iWantToGetThisExceptionOutside; } } }); assertTrue(taskStarted.await(60,...