• Post Reply Bookmark Topic Watch Topic
  • New Topic

Locking String Objects  RSS feed

 
Jared Folino
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!