[Abhijit]: Thnx Henry but these atomic variables you talking about may internally use sync blocks. Except that they don't. You can investigate the source code yourself if you like.
[Abhijit]: And Ok I understand that there is no opcode for ++ or -- but what I am trying to achieve is the threads I talked about can they make simultaneous changes to the variable. Certainly it's possible for threads to make simultaneous changes to the variable. But if you reject known thread-safe techniques like using synchronization or using atomic variables, there's a good chance that your simultaneous changes can result in invalid data or nonsensical results.
[Abhijit]: Or can i use a local variable instead of static so that multiple threads cant access it at same time while incrementing If you use a
local variable, different threads will not share data at all; each will see its own copy. Perhaps you meant
instance variable. If you do that, and protect it with synchronization, then different threads may be able to execute concurrently, if they are operating on different instances. Generally the decision to use static or instance variables depends on the nature of the data itself - what does it represent? Some things are naturally static, and some are not. Synchronization should not be your driving concern here.
In your original code
if X is static, then it makes no sense at all to try to protect it with a "synchronized (this)" - "this" implies an instance, which may or may not exist. And two different threads should
not be allowed to execute this method simultaneously just because they are using different instances - because X has nothing to do with those instances; it's a static variable. Instead, to protect access to a static variable,
you should typically synchronize on the Class instance for the current class. This is an object shared by the entire class. It's also possible to sync on some other shared object, but using the Class object is the most common choice - and that's what static synchronized methods do.
Or as Henry suggests, it's certainly possible to use atomic variables. But if you use synchronzation, be sure to sync on an appropriate object.
[ December 25, 2007: Message edited by: Jim Yingst ]