volatile keyword in JDK5

From: pool0078@xxxxxxx (Min-Koo Seo)
Newsgroups: comp.programming.threads
Subject: volatile keyword in JAVA
NNTP-Posting-Host: 165.132.121.251
Message-ID: <4c458db8.0412240150.2167a1f2@posting.google.com>

Hello.

I have some question regarding volatile keyword in JDK 5.

AFAIK, volatile keyword gurantees atomic reads/writes only.

(1) Regarding increment of volatile int.

Hence, the codes like:

volatile int i=0;
i += 3;

is not thread-safe because it reads and modifies in ‘i += 3.’

Then, what about “i++”? Is i++ thread safe?

(2) Regarding volatile local variable.

Following code fails to compile:
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;

public class AtomicExample {

public static void main(String[] args) {

volatile int vi = 0;

for (int i = 0; i < 10; i++) { vi += 1; System.out.println("vi=" + i); } } } --- AtomicExample.java:8: illegal start of expression volatile int vi = 0; ^ 1 error But following codes is compiled very well: import java.util.concurrent.*; import java.util.concurrent.atomic.*; public class AtomicExample { static volatile int vi = 0; public static void main(String[] args) { for (int i = 0; i < 10; i++) { vi += 1; System.out.println("vi=" + i); } } } What's the reason of compilation failure? Sincerely, Minkoo Seo ---- 글쓴이:David Hopwood (david.nospam.hopwood@blueyonder.co.uk) 제목:Re: volatile keyword in JAVA View this article only 뉴스그룹:comp.programming.threads 날짜:2004-12-24 08:45:16 PST Min-Koo Seo wrote: > Hello.
>
> I have some question regarding volatile keyword in JDK 5.
>
> AFAIK, volatile keyword gurantees atomic reads/writes only.
>
> (1) Regarding increment of volatile int.
>
> Hence, the codes like:
>
> volatile int i=0;
> i += 3;
>
> is not thread-safe because it reads and modifies in ‘i += 3.’
>
> Then, what about “i++”? Is i++ thread safe?

‘i++’ is exactly equivalent to ‘i += 1’ or ‘i = i+1’: it reads and
then writes i in two operations.

> (2) Regarding volatile local variable.

‘volatile’ for local variables could not possibly have any effect,
because local variables in Java cannot be aliased, and therefore
cannot be accessed by more than one thread. (Inner classes may
appear to be an exception, but can actually only access a copy of
the variable.)

The volatile declaration is therefore disallowed.

호.. 궁금증이 풀렸음.
로컬 변수가 공유안된다는 것을 알면서도 이를 volatile 연결해서 생각 못하는 실수를..

Similar Posts:

Post a Comment

Your email is never published nor shared.