• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Locking String Objects

 
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 ]
 
author
Posts: 23879
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux 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 ]
 
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
    Bookmark Topic Watch Topic
  • New Topic