development

Java에서 volatile 키워드를 정확히 언제 사용합니까?

big-blog 2020. 9. 16. 08:08
반응형

Java에서 volatile 키워드를 정확히 언제 사용합니까? [복제]


이 질문에 이미 답변이 있습니다.

" 언제 Java에서 'volatile'을 사용해야합니까? " 읽었 지만 여전히 혼란 스럽습니다. 언제 변수를 휘발성으로 표시해야하는지 어떻게 알 수 있습니까? 휘발성이 필요한 것에 휘발성을 생략하거나 그렇지 않은 것에 휘발성을 두는 것이 잘못되면 어떻게합니까? 멀티 스레드 코드에서 어떤 변수가 휘발성이어야하는지 알아낼 때 경험상의 규칙은 무엇입니까?


기본적으로 여러 스레드에서 멤버 변수에 액세스하도록 허용하지만 복합 원 자성이 필요하지 않을 때 사용합니다 (올바른 용어인지 확실하지 않음).

class BadExample {
    private volatile int counter;

    public void hit(){
        /* This operation is in fact two operations:
         * 1) int tmp = this.counter;
         * 2) this.counter = tmp + 1;
         * and is thus broken (counter becomes fewer
         * than the accurate amount).
         */
        counter++;
    }
}

위는 복합 원 자성 필요 하기 때문에 나쁜 예 입니다.

 class BadExampleFixed {
    private int counter;

    public synchronized void hit(){
        /*
         * Only one thread performs action (1), (2) at a time
         * "atomically", in the sense that other threads can not 
         * observe the intermediate state between (1) and (2).
         * Therefore, the counter will be accurate.
         */
        counter++;
    }
}

이제 유효한 예 :

 class GoodExample {
    private static volatile int temperature;

    //Called by some other thread than main
    public static void todaysTemperature(int temp){
        // This operation is a single operation, so you 
        // do not need compound atomicity
        temperature = temp;
    }

    public static void main(String[] args) throws Exception{
        while(true){
           Thread.sleep(2000);
           System.out.println("Today's temperature is "+temperature);
        }
    }
}

자, 왜 그냥 사용할 수 private static int temperature없습니까? 사실 당신은 할 수 있습니다 (당신의 프로그램이 폭발하지 않을 것이라는 의미에서), 그러나 temperature다른 스레드 의한 변경 은 메인 스레드에 "보이지 않을 수도"있습니다.

기본적으로 이것은 당신의 앱이 가능하다는 것을 의미합니다. 사용 하지 않으면Today's temperature is 0 영원히 계속 작성 합니다 (실제로 값은 결국 표시되는 경향이 있습니다. 그러나 불완전하게 구성된 객체 등으로 인해 발생하는 불쾌한 버그로 이어질 수 있으므로 필요할 때 휘발성을 사용하지 않을 위험이 없습니다.) ).volatile

If you put volatile keyword on something that doesn't need volatile, it won't affect your code's correctness (i.e. the behaviour will not change). In terms of performance, it will depend on the JVM implementation. In theory you might get a tiny performance degradation because the compiler can't do reordering optimisations, have to invalidate CPU cache etc., but then again the compiler could prove that your field cannot ever be accessed by multiple threads and remove the effect of volatile keyword completely and compile it to identical instructions.

EDIT:
Response to this comment:

Ok, but why can't we make todaysTemperature synchronized and create a synchronized getter for temperature?

You can and it will behave correctly. Anything that you can with volatile can be done with synchronized, but not vice versa. There are two reasons you might prefer volatile if you can:

  1. Less bug prone: This depends on the context, but in many cases using volatile is less prone to concurrency bugs, like blocking while holding the lock, deadlocks etc.
  2. More performant: In most JVM implementations, volatile can have significantly higher throughput and better latency. However in most applications the difference is too small to matter.

Volatile is most useful in lock-free algorithms. You mark the variable holding shared data as volatile when you are not using locking to access that variable and you want changes made by one thread to be visible in another, or you want to create a "happens-after" relation to ensure that computation is not re-ordered, again, to ensure changes become visible at the appropriate time.

The JMM Cookbook describes which operations can be re-ordered and which cannot.


volatile keyword guarantees that value of the volatile variable will always be read from main memory and not from Thread's local cache.

From java concurrency tutorial :

Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable

This means that changes to a volatile variable are always visible to other threads. It also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.

Regarding your query:

How do I know when I should mark a variable volatile? What are the rules of thumb when figuring out what variables should be volatile in multithreaded code?

If you feel that all reader threads always get latest value of a variable, you have to mark variable as volatile

If you have one writer thread to modify the value of variable and multiple reader threads to read the value of variable, volatile modifier guarantees memory consistency.

If you have multiple threads to write and read variables, volatile modifier alone does not guaranty memory consistency. You have to synchronize the code or use high level concurrency constructs like Locks, Concurrent Collections, Atomic variables etc.

Related SE questions/articles:

Volatile variable explanation in Java docs

Difference between volatile and synchronized in Java

javarevisited article


The volatile can also be used to safely publish immutable objects in a multi-threaded Environment.

Declaring a field like public volatile ImmutableObject foo secures that all threads always see the currently available instance reference.

See Java Concurrency in Practice for more on that topic.


Actually disagree with the example given in the top voted answer, to my knowledge it does NOT properly illustrate volatile semantics as per the Java memory model. Volatile has way more complex semantics.

In the example provided, the main thread could continue to print "Today's temperature is 0" forever even if there is another thread running that is supposed to update the temperature if that other thread never gets scheduled.

A better way to illustrate volatile semantics is with 2 variables.

For simplicity's sake, we will assume that the only way to update the two variables is through the method "setTemperatures".

For simplicity's sake, we will assume that only 2 threads are running, main thread and thread 2.

//volatile variable
private static volatile int temperature; 
//any other variable, could be volatile or not volatile doesnt matter.
private static int yesterdaysTemperature
//Called by other thread(s)
public static void setTemperatures(int temp, int yestemp){
    //thread updates yesterday's temperature
    yesterdaysTemperature = yestemp;
    //thread updates today's temperature. 
    //This instruction can NOT be moved above the previous instruction for optimization.
    temperature = temp;
   }

the last two assignment instructions can NOT be reordered for optimization purposes by either the compiler, runtime or the hardware.

public static void main(String[] args) throws Exception{
    while(true){
       Thread.sleep(2000);
       System.out.println("Today's temperature is "+temperature); 
       System.out.println("Yesterday's temperature was "+yesterdaysTemperature );
 }
}

Once the main thread reads the volatile variable temperature (in the process of printing it),

1) There is a guarantee that it will see the most recently written value of this volatile variable regardless of how many threads are writing to it, regardless of which method they are updating it in, synchronized or not.

2) If the system.out statement in the main thread runs, after the time instant at which thread 2 has run the statement temperature = temp, both yesterday's temperature and todays temperature will be guaranteed to print the values set in them by thread 2 when it ran the statement temperature=temp.

This situation gets a LOT more complex if a) Multiple threads are running and b) There are other methods than just the setTemperatures method that can update the variable yesterday's temperature and todays temperature that are actively being called by these other threads. I think it would take a decent size article to analyze the implications based on how the Java Memory Model describes the volatile semantics.

In short, attempting to just use volatile for synchronization is extremely risky, and you would be better off sticking to synchronizing your methods.


http://mindprod.com/jgloss/volatile.html

"The volatile keyword is used on variables that may be modified simultaneously by other threads."

"Since other threads cannot see local variables, there is never any need to mark local variables volatile. You need synchronized to co-ordinate changes to variables from different threads, but often volatile will do just to look at them."


voltalie Means Keep changing value.The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory".In other words Java compiler and Thread that do not cache value of this variable and always read it from main memory.

참고URL : https://stackoverflow.com/questions/3488703/when-exactly-do-you-use-the-volatile-keyword-in-java

반응형