[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Concurrency Questions
On Wed, 2001-10-24 at 08:04, Dale Bronk - Windscape wrote:
> Hello,
>
> I have two questions. Please assume multiprocessor machines with each
> thread running on separate cpu's. Also, if you can point me to any
> reference that backs your opinion/fact would be great. Am I safe on both of
> the following?
>
> 1. Lets say I have the following code:
>
> public class MyTest extends Thread
> {
> static int i = 0;
>
> // Please not NO sync's
> run()
> {
> i++;
> }
> }
>
> Now let's say that I spawn 2 of these and they are on different cpu's and
> they both execute i++ at the same time. Is there EVER a chance that the
> result of i can EVER be 1 or will it always be 2.
>
i++ is not an atomic operation. If you do not synchronize you may/will
run into trouble.
>
> 2. Now here is another code snippet:
>
> static ArrayList myStaticList = null;
> public ArrayList getList(boolean shouldRefresh)
> {
> if (shouldRefresh)
> {
> // Not only sync on refreshing, not getting
> synchronized (someLockObject)
> {
> ArrayList newList = new ArrayList();
> // Code here to get new list from database and fill newList
> myStaticList = newList;
> }
> }
> return myStaticList;
> }
>
> My question is that let's say that one thread (different cpu) is executing
> return myStaticList at the same time as another thread is executing
> myStaticList = newList. Is it possible that the return myStaticList will
> EVER return a half/limbo state object or worse yet a Dr. Watson or
> something?
I think your question is whether a reference assignment is atomic. Yes,
it is.
Randy
>
> Help is wanted and appreciated.
>
> Thanks,
> Dale
>
>
>
>
>
>
>
>
>
>