Article View: borland.public.jbuilder.java.language
Article #7661Nature of synchronized{ } (thread newbie)
From: Zoltan Grose
Date: Mon, 04 Jun 2001 06:21
Date: Mon, 04 Jun 2001 06:21
50 lines
2421 bytes
2421 bytes
I'm going to be diving into servlet programming shortly and I feel now is a
good time to wrap my brain around threads and the keyword synchronized.
From the reading I have done and the examples I have seen, I believe I can
summarize the use of synchronized in this way:
"If a method accesses (either reads from or writes to) a variable that one
reasonably expects not be constant and that variable is not local to the
method, the accessing code should be synchronized."
For example, I believe this code to be thread-safe since all of the
variables are local.
public class MyClass {
public int performCalculation(int x, int y) {
int temp1 = 0; int temp2 = 0;
temp1 = y + 5;
temp2 = x / 3;
return temp1 + temp2;
}
}
I believe this code to be thread-unsafe since temp2 is not local to the
method and could potential be modified at any point during any execution of
performCalculation.
public class MyClass {
int temp2 = 0;
public void setTemp2(int temp2) {this.temp2 = temp2;}
public int performCalculation(int x, int y) {
int temp1 = 0;
temp1 = y + 5;
temp2 = x / 3;
return temp1 + temp2;
}
}
The second example would be made thread-safe again by wrapping the unsafe
section in a sychronized block.
synchronized {
temp2 = x / 3;
return temp1 + temp2;
}
Am I on the right track? (Am I in the right newsgroup?) My background is in
VB, so threads are one of the new concepts I'm trying to deal with before I
get to deep. Thanks in advance.
-zoltan
Technical Details
Message-ID:
<3b1b28df$1_2@dnews>Path:
arc1-ca.pugleaf.net!archiver1.google.com!newsfeed.google.com!sn-xit-02!supernews.com!newsfeed.direct.ca!look.ca!netnews.com!fr.clara.net!heighliner.fr.clara.net!newsfeed01.sul.t-online.de!t-online.de!dnewsShow Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: f74b3,ec3ad0c2eb0c6632,start
X-Google-Attributes: gidf74b3,public
X-Google-ArrivalTime: 2001-06-03 23:42:36 PST
From: "Zoltan Grose" <zgrose@pacbell.net>
Newsgroups: borland.public.jbuilder.java.language
Subject: Nature of synchronized{ } (thread newbie)
Date: Sun, 3 Jun 2001 23:21:37 -0700
Lines: 53
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 5.50.4522.1200
X-MimeOLE: Produced By Microsoft MimeOLE V5.50.4522.1200
NNTP-Posting-Host: 63.193.228.78
Message-ID: <3b1b28df$1_2@dnews>
X-Trace: dnews 991635679 63.193.228.78 (3 Jun 2001 23:21:19 -0700)
Path: arc1-ca.pugleaf.net!archiver1.google.com!newsfeed.google.com!sn-xit-02!supernews.com!newsfeed.direct.ca!look.ca!netnews.com!fr.clara.net!heighliner.fr.clara.net!newsfeed01.sul.t-online.de!t-online.de!dnews