30

Can I declare something like this??

static volatile boolean first=false;
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
Saurabh Kumar
  • 16,353
  • 49
  • 133
  • 212
  • 21
    have you tried it? what happened? – Mat Mar 27 '11 at 19:35
  • 13
    This site is not a replacement for google and reading the docs. It is not a site to bring you "ready-made" answers. You're supposed to ask specific questions related to programming that you can't find answers to easily via a normal search. You're also supposed to at least try to make your questions clear (spelling, capitalization, code formatting count) if you want good answers. You could have found the answer to that question in about 30s of googling. – Mat Mar 27 '11 at 19:43
  • 1
    @Saurabh: that's the point exactly. What's the point asking the question if you can easily find the answer yourself? This site is not intended to for people to ask questions because they feel like it, it's to help people with problems they are having, preferably only after they've had a go dealing with it themselves. Rather than spend 30s finding an answer yourself, you've instead you've used up several minutes of *other* people's time to answer something you should be able to answer yourself. – Mac Mar 27 '11 at 19:57
  • 2
    The only thing you can't have with `volatile` is `final`. `static` can be used with any other modifier even `transient` ;) – Peter Lawrey Mar 27 '11 at 19:57
  • @Saurabh: Additionally, for this question the only valid answers would be **yes** or **no**, which both are too short for an answer. If you had asked "Why can I ..." or "What is the meaning of ...", it would have been a useful question. – Paŭlo Ebermann Mar 27 '11 at 20:11
  • 2
    I wrote an answer about the [difference between static and volatile](http://stackoverflow.com/questions/2423622/volatile-vs-static-in-java/7943472#7943472) – stivlo Oct 30 '11 at 05:35
  • by the way, this is now a good referenced answer that help me a lot when I lost 30 seconds of my time by searching it before asking on stackoverflow ;) – Jerome Cance Nov 14 '14 at 18:13
  • Ironically, this is now the first hit in a Google search for 'static volatile boolean'. – Tristan Angieri Aug 11 '16 at 22:15

5 Answers5

75

To expand on Michael's comment.

static simply means not associated with an instance of the containing class.

volatile simply means that the value may be changed by other threads without warning.

So your question boils down to "can a field not associated with an instance of the containing class be changed by another thread without warning?"

As Michael pointed out, the answer to that question is yes. Instance association is orthogonal to concurrent modification.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
  • 1
    Out of curiosity, what happens if we introduce a `final` there? – Skynet Mar 17 '15 at 09:22
  • 1
    @Skynet, The [JLS](http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.1.4-210) says "It is a compile-time error if a final variable is also declared volatile." – Mike Samuel Mar 18 '15 at 17:54
  • I quite disagree with that description of `volatile`, what do you mean by "without warning"? What kind of warning do I get when I don't use volatile and change value by some other thread? Description by @Håvard S is more correct – Tibor Blenessy Mar 03 '17 at 15:58
  • @TiborBienessey, `volatile` is hard to cover succinctly. One of the use cases for `volatile` in C is to identify memory locations written by hardware devices -- no threads needed. "Accessed frequently by multiple threads" doesn't really get at the core of it either since if all those threads are readers, caching is fine. "Can not cache" is better. "Write back immediately after mutating" is false -- there's no such thing as "immediate," just "before next access by same thread." By "without warning" I'm trying to convey that other accessors won't use common conventions like monitors. – Mike Samuel Mar 04 '17 at 21:38
26

Yes, you can.

A static variable in Java is stored once per class (not once per object, such as non-static variables are). This means all your objects (and static methods) share the same variable.

Declaring a variable as volatile (be it static or not) states that the variable will be accessed frequently by multiple threads. In Java, this boils down to instructing threads that they can not cache the variable's value, but will have to write back immediately after mutating so that other threads see the change. (Threads in Java are free to cache variables by default).

Håvard S
  • 23,244
  • 8
  • 61
  • 72
  • 1
    An additional interesting question would be: Is there a difference between a `static` and a `static volatile` variable? I once read that static variables do not get cached by threads so declaring a static variable with volatile is not really necessary? Any comments on this? – basZero Apr 09 '14 at 12:03
  • 4
    There is indeed a difference, and it is deduced from the answer: A `static` variable is stored once per class. A `static volatile` variable is stored once per class _and_ will be accessed frequently by multiple threads, i.e. reads cannot be cached. – Håvard S Apr 09 '14 at 18:15
10

Sure. The effects of the two modifiers are completely orthogonal.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
0

yes, you can.

static boolean first=false;

When you are declaring a static variable, there will be only one copy for all the objects, no matter how many objects of the class are created. Each thread would have its own cached copy.

If it is volatile, Thread should go to memory each time and gets the updated value of the variable.

static volatile boolean first=false;

It will

force the thread to read each time the memory directly

to find the value of the variable first.

Azhagu Surya
  • 132
  • 1
  • 1
  • 17
0

As per the question, yes we can but in that case we need to handle all the scenario.

Access a static value through multiple threads, each thread can have it’s local cached copy! To avoid this you can declare the variable as static volatile and this will force the thread to read each time the global value. However, volatile is not a substitute for proper synchronisation

private static volatile int cnt= 0;

private void checkCnt() {
     cnt+= 1;
     // some conditions
     // some code
     cnt -= 1;
}

Executing checkCnt concurrently many times the final value of cnt different from what we expect! To solve the problem, we’ve to implement a lock to keep track of increment/decrement

private static final Object lock = new Object();
private static volatile int cnt= 0;

private void checkCnt() {
     synchronized (lock) {
         cnt += 1;
     }
     //some conditions
     //some code
     synchronized (lock) {
         cnt -= 1;
     }
}

Not sure is this the right way but by this we can manage the things and use static with volatile. Please provide inputs, if there is better way.

Atul
  • 3,043
  • 27
  • 39