Here is a good tutorial on Java concurrency : Concurrency
The most common way of way of handling concurrent modifications is by using the synchronized key word, but that is not the only way to do it. There is also methods based on message passing like the actor model and there is atomic variable
The 5 levels of thread safety. It defines objects that are the best/easiest to use in a multi-threaded environment to the worst/hardest.
1. Immutable : The object can't be modified once created. This is the most safe level. No matter how many threads access this object you won't run into any problems.
2. Thread-safe : The object contains enough internal synchronization (synchronized method) to be used without problems by multiple threads.
3. Conditionally thread-safe : Same as thread-safe except that under some circumstances, you will need to provide external synchronization (outside of that object)
4. Thread-Compatible : Can be used in multi-threaded environment but it is up to the programmer to do the synchronization
5. Thread-hostile : Can't be used in multi-threaded envrionment (Ex.: Thread.stop() - That method was deprecated because it releases the lock when it is called. Hence it could leave an object into an invalid state)
People usually think that the method Collections.synchronizedList(new ArrayList()) will return a thread-safe collection. But that is not true. It is conditionnaly thread-safe. That is true for almost all Java default ''synchronized'' collections. Here is a list of collections that are Thread-safe : Concurrent Collections
Vectors are conditionally thread-safe. That means that most of the time you don't need to provide external synchronization but in some cases you might. One case where you need external synchronization is when iterating over the Vector and modifying it.
Collection.getSynchronizedCollection() - (or something like that) are also conditionnally thread-safe : meaning that you have to provide external synchronization for some operation.
ArrayList is thread compatible : meaning that if you want to use it in a multi-threaded environment you have to provide all the synchronizationThe Best Advice On Using Concurrency
... is to avoid using concurrency at all
if you can help it. Threads are extremely difficult to debug, behaving and interacting in very complex ways that are often counterintuitive or seemingly completely indeterministic. They are also not nearly as effective as you'd like to hope in a typical SMP desktop system: two threads does not equal twice the computation, typically. You'll be lucky to achieve a fraction of an increase, for a great deal of extra complexity.
This wiki entry has had 8 revisions with contributions from 4 members.