What is the differences between volatile and static keyword?

Static variable keeps single value for a thread but volatile keeps single value for all threads(example here)

Most of the scenario constants are declared as static and also constant data will be the same for all threads so why constants are not declared as volatile

when we can use volatile keyword in java


I think you've misunderstood both static and volatile.

static is just about having a single field across the whole type. It has nothing to do with threads - it's just about whether there's one field for the type (static) or one field for each instance of the type (non-static).

volatile is just about what guarantees there are around when changes made by one thread are visible in other threads. This has nothing to do with whether the field is static or not. From section of the JLS:

The Java programming language allows threads to access shared variables (§17.1). As a rule, to ensure that shared variables are consistently and reliably updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that, conventionally, enforces mutual exclusion for those shared variables.

The Java programming language provides a second mechanism, volatile fields, that is more convenient than locking for some purposes.

A field may be declared volatile, in which case the Java Memory Model ensures that all threads see a consistent value for the variable (§17.4).

(Section 17.4 has a lot more detail.)

Need Your Help

Nokogiri and XPath help

ruby xml xpath nokogiri

Admittedly, I'm a Nokogiri newbie and I must be missing something...