I believe that is a question difficult to answer in a forum. And I am pretty sure that reading a couple of books on multithreading programming with
Java will indeed help you master this concept.
I am far from being an expert, but I have read Mr. Henry Wong book (who by chance is an honorable member of the JavaRanch) and I would recommend it to you:
Java Threads, 3rd Edition I think that when you have a class member that can be modified by multiple threads concurrently, you have to synchronize access to your variables, regardless of the modification is happening in a
static or a non-static context.
For instance, I could have a class that counts how many instance of it are created.
In this case the variable count could be incremented by multiple threads concurrently instantiating a new class Counter. How to synchronize access to the variable count from a non-static context?. As far as I understand, there are several mechanism to do that, all of them are approaches with different adventages and disadventages.
One alternative in this case is to declare the
variable as volatile (but be careful volatile is not the cure of all evil). If you are using JDK 1.5 you could also use an
atomic object (i.e AtomicInteger).
Another option could be to use a synchronized block to get a lock on the class.
Or you could declare a synchronized method for the increment operation:
Or if using JDK 1.5 you could also use the new Lock objects provided in the java.util.concurrent package.
And I am pretty sure there could even be other possibilities. Therefore, I believe there is not a single way to do it, and it all could depend on the particular problem you want to solve.
[ October 25, 2006: Message edited by: Edwin Dalorzo ]