• Post Reply Bookmark Topic Watch Topic
  • New Topic

String as a lock  RSS feed

 
Roger Zhao
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,all:
Given:

Primitives don't have locks and therefore can not be used to synchronize threads. Here String s is used for synchronize as a lock.

String instance itself is shared between the two threads and therefore the lock on the String is also shared between the two threads. The shared lock on the shared String literal will provide effective synchronization.

What is the share relationship here?
Thanks,
Roger
[ September 04, 2003: Message edited by: Roger Zhao ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String literals like "" are automatically shared, even across classes; i.e., all occurrences of the literal "" refer to the same object. The code

will print "true", whereas

because it creates two separate String objects, prints "false".
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!