aspose file tools
The moose likes Threads and Synchronization and the fly likes Locking String Objects Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Locking String Objects" Watch "Locking String Objects" New topic
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
    
  19

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
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Locking String Objects
 
Similar Threads
synchronized method
Thread ...
Threading and collections problem.Pl help
ExamLab Thread question
Threads-synchronized blocks,Valentine &Michael and Others,Help needed