There seems to be a lot of fuss about multicore and java. While some people say that java support is not good enough, it definitely seems to be an area to look forward to. There seems to be many techniques to improve performance of concurrent programs.
Any tips/advices about programming in a multi core scenario is appreciated.
Look into the new Java concurrency facilities (in the java.util.concurrent
package) which have been added in Java 5. It provides functionality that is more high-level than regular Thread
s which will make it easier (and less error-prone) to write concurrent applications. The Lesson: Concurrency of The Java Tutorials would be a good place to start.
So far, I've only used the ExecutorService
, which allows can produce thread pools, to which new tasks can be handed off in units of Runnable
s or Callable
s (which can return values after execution as Future
s), and the actual threading code is handled by the ExecutorService
.
For example, performing some calculation using a thread pool of 2 threads, and getting the result can be as simple as:
ExecutorService es = Executors.newFixedThreadPool(2);
Future f1 = es.submit(new Callable<Integer>() {
public Integer call()
{
// Do some processing...
return someInteger;
}
});
Future f2 = es.submit(new Callable<Integer>() {
public Integer call()
{
// Do some processing...
return someInteger;
}
});
Integer firstInteger = f1.get();
Integer secondInteger = f2.get();
In the above (untested) code, all I have to worry about is making a couple of Callable
s and submit
ing it to the ExecutorService
and later on, using the Future
s to retrieve the result.
The catch is, once the get
method of the Future
is called, if the processing isn't complete, the program will stop until the result of the Future
can be retrieved. So, in this example, even if the result of f2
is available before f1
, the program will wait until the result of f1
is available.
In terms of reading material, on my list of books to purchase soon is Java Concurrency in Practice by Brian Goetz, which comes up often when concurrency in Java is brought up.
The Concurrency Utilities page from the Java 5 documentation has more information as well.
The best tip has got to be: get your synchronization correct!
This may seem somewhat obvious but an understanding of the Java Memory Model is vital, particularly how volatile and final fields work, how synchronized acts as both a mutex and a memory barrier and then the new java.util.concurrent
constructs as well
Always a good tip - if most of your classes are immutable everything becomes so much easier as immutability removes the need to worry about locks from many to few places of concern.
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