[78] in java-interest
Re: problem with synchronize( )
daemon@ATHENA.MIT.EDU (Arthur van Hoff)
Wed May 10 18:24:45 1995
Date: Wed, 10 May 1995 14:52:46 -0700
From: Arthur.Vanhoff@Eng.Sun.COM (Arthur van Hoff)
To: java-interest@java.Eng.Sun.COM
Hi Suresh,
> >> In the following, the first synchronize() statement completely confuses
> >> javac, while the second one works. Why is this ?
> >>
> >> int i;
> >> int j[] = new int[5];
> >> .....
> >> synchronize(i)
> >> { i = 3;
> >> ......
> >> }
> >> ......
> >> synchronize(j)
> >> { j[1] = 3;
> >> .....
> >> }
> >
> >The problem is that you can only synchronize on objects. Unfortunately
> >integers aren't objects so you can't synchronize on them. It is actually
> >very unusual that you have to use the synchronize statement, it is often
> >enough to use the synchronize modifier on the methods you are in.
>
> If I understand correctly, synchronize methods serialize access only to
> the instance variables of their own class/object, and hence if I want to
> serialize access to instance vars of other classes, I have to explicitly use
> synchronize.
>
> Is this correct ?
That is correct. But I would not recommend direct access to another object's
instance variables. Instead just add a synchronized method to that object to
do the work. It should be rare that you need to use the synchronize statement.
> BTW, if ints are not classes nor objects, what are they ?
> I thought everything in Java was a class or an object.
Unfortunately number and booleans are not objects. This is mainly for
efficiency reasons. There are classes that let you encapsulate a number
in a class though...
Have fun,
Arthur van Hoff (avh@eng.sun.com)
http://java.sun.com/people/avh/
Sun Microsystems Inc, M/S UPAL02-301,
100 Hamilton Avenue, Palo Alto CA 94301, USA
Tel: +1 415 473 7242, Fax: +1 415 473 7104
-
Note to Sun employees: this is an EXTERNAL mailing list!
Info: send 'help' to java-interest-request@java.sun.com