First of all
Regular disclaimer: programming in any language at the same time, using any level of abstraction, is hard and complex and has many risks. Take into account:
- Concurrent programming complicates any size application
- Critical Partition Test Modules are Tough and Sometimes Impossible
- Reproduction of errors that occur in parallel code is very difficult and highly dependent on the architecture, OS style, version, etc.
Java Concurrent API
Java has come a long way in making concurrent programming easier for developers. In most cases, you will see that java.util.concurrent has most of the abstractions you will need:
Runnable and Thread object that you can expand. Just enter the code and you have a thread ready to run.- A good set of
Executors : persistent pool, dynamic pool, scheduled or any other. Just throw Runnable at it, and everything else. Semaphore s and locks of all kinds will eliminate the need for common locking methods.- Built-in
wait() and notify() API for all objects.
Using
The only thing left for you as a software engineer is to make sure that you are writing the correct one . So you should be aware of dangerous situations that you could expose yourself to:
- A dead end is a situation where two or more threads are waiting on unordered resources, providing an endless waiting cycle.
- Livelock - two or more threads that politely try to concede to each other on a shared resource, but ultimately do not accept it (consider two people in the corridor going to each other and constantly moving together from side to side)
- Starvation is a single thread that occupies most or all of one common resource, thereby depriving other threads of access to it.
The main point (or when to use it)
Use threads only when concurrency will directly improve the behavior of your applications.
If you expect a resource related to IO / network / hardware, DO , create a thread to continue with other activities.
If you are just trying to elegantly separate the processor related calculations, DO NOT use , use threads. You can simply degrade your performance.
If you use threads, make sure that you carefully consider the risks and check three times, you did not miss any exceptional situations.
Useful (online) resources
The quickest way to get into things is to do a Sun concurrency tutorial . Other than that, get a good book.
Good luck :)
Yuval Adam
source share