I am writing an optimazation algorithm which creates about 100 threads. Currently, I start them all at one time (for-loop) and after that I tell every thread that it should join().
My problem is now that each thread uses to much memory so the heap space exception won't take long. I want some kind of scheduling but don't know how to implement it.
I have something like this in mind: start 10 threads and every time one of these finishes start a new one. So that there are allways running 10 threads at a time until no thread is left.
Has someone an idea or knows how to realize something like this?
Thank you very much and regards from Cologne
Marco
Each core can only run 1 thread at a time, i.e. hyperthreading is disabled. So, you can have a total maximum of 20 threads executing in parallel, one thread per CPU/core.
Some notes when we use concurrency and parallelism in Java A thread is only executing one task at a time. There is no parallel execution of tasks going in parallel threads/CPUs. An application can also be parallel but not concurrent.
What is Memory Management In Java? Memory management in Java is the process of allocating working memory space to new objects and properly removing unreferenced objects to create space for those new object allocations.
Threads are components of a process, which can run parallely. There can be multiple threads in a process, and they share the same memory space, i.e. the memory space of the parent process. This would mean the code to be executed as well as all the variables declared in the program would be shared by all threads.
Use a ThreadPoolExecutor with an appropriate maximum pool size.
Here's an example to get you started. First, what you'll need to import:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
And then what you need to put inside your method:
ExecutorService pool = Executors.newFixedThreadPool(10);
for(final Task task: tasks) {
pool.execute(new Runnable() {
@Override
public void run() {
task.execute();
}
});
}
pool.shutdown();
while(!pool.awaitTermination(1, TimeUnit.SECONDS)) {
System.out.println("Waiting for tasks to shutdown");
}
Some notes about the above:
java.util.concurrent.atomic
are
quite good if you have shared state
you need to update (e.g. if you want
to have a counter for how many tasks
you've processed).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With