http://www.vogella.de/articles/JavaConcurrency/article.html
To make a class immutable make
-
all its fields final
-
the class declared as final
-
the this reference is not allowed to escape during construction
-
Any fields which refer to mutable data objects are
-
private
-
have no setter method
-
they are never directly returned of otherwise exposed to a caller
-
if they are changed internally in the class this change is not visible and has no effect outside of the class
-
An immutable class may have some mutable data which is uses to manages its state but from the outside this class nor any attribute of this classes can get changed.
The base means for concurrency are "java.lang.Threads". Each thread will execute an object of type "java.lang.Runnable". Runnable is an interface with defines only the one method "run()". This method is called by "Thread" and contains the work which should be done. Therefore the "Runnable" is the task to perform. The Thread is the worker who is doing this task.
Runnable task = new MyRunnable(10000000L + i);
Thread worker = new Thread(task);
// We can set the name of the thread
worker.setName(String.valueOf(i));
// Start the thread, never call method run() direct
worker.start();
Using Threads directly has the following disadvantages.
-
Creating a new thread causes some performance overhead
-
Too many threads can lead to reduced performance, as the CPU needs to switch between these threads.
-
You cannot easily control the number of threads, therefore you may run into out of memory errors due to too many threads.
The "java.util.concurrent" package offers improved support for concurrency compared to threads. The java.util.concurrent package helps solving several of the issues with threads.
The Executor framework provides example implementation of the
java.util.concurrent.Executor interface, e.g.
Executors.newFixedThreadPool(int n) which will create n worker
threads. The ExecutorService adds lifecycle methods to the Executor,
which allows to shutdown the Executor and to wait for termination.
ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
for (int i = 0; i < 500; i++) { Runnable worker = new MyRunnable(10000000L + i); executor.execute(worker); } // This will make the executor accept no new threads // and finish all existing threads in the queue executor.shutdown(); // Wait until all threads are finish while (!executor.isTerminated()) {
import java.util.concurrent.atomic.AtomicInteger;
Non Blocking Algorithms
. The fork-join framework allows you to
distribute a certain task on several workers and when wait for the
result.
No comments:
Post a Comment