| Author |
Locking String Objects
|
Jared Folino
Greenhorn
Joined: Apr 27, 2007
Posts: 25
|
|
I have a class that has two synchronized methods. One sets the Sring, and then prints it 3 times. The next method changes the String to "concurrency error" but that is the end of the method. Now as they are locking the same object the "concurreny error" and that is the end of the method. Theorectically as they lock the same object "concurrency error" should never print as the other synchronized method changes it back. This is not the case. Can somneone please help me? [Henry: Added Code Tags] [ April 29, 2007: Message edited by: Henry Wong ]
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16687
|
|
I have a class that has two synchronized methods. One sets the Sring, and then prints it 3 times. The next method changes the String to "concurrency error" but that is the end of the method. Now as they are locking the same object the "concurreny error" and that is the end of the method. Theorectically as they lock the same object "concurrency error" should never print as the other synchronized method changes it back. This is not the case. Can somneone please help me?
First, [DELETED: oh, I see what you are trying to describe. Ignore this point. See the next point for your answer.] Second, synchronization is based on objects, not references... This... is not a good idea. As any other thread that calls the same block will lock on a different object, as you have changed it. Same goes for stuff like... Basically, since you are constantly changing the objects, the threads are locking on different objects. Hence, it is not threadsafe. Henry [ April 29, 2007: Message edited by: Henry Wong ]
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Burkhard Hassel
Ranch Hand
Joined: Aug 25, 2006
Posts: 1274
|
|
Howdy, cowboys! What Henry forgot to mention (presumably because he thinks everybody knows it): Strings are immutable. Ever heard? Use a StringBuffer instead. I tried it out, it works. Yours, Bu.
|
all events occur in real time
|
 |
 |
|
|
subject: Locking String Objects
|
|
|