Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

synchronized (Class.forName("x.y"))  RSS feed

 
Renata fonseca
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is using synchronized block code with Class.forName() slow? Are there some other (and good) way to synchronize a code block where 2 or more different objects can enter in that block code?
Ie.:
void writeToFile(){
....
synchronized(Class.forName("x.y"))
{
// code that open some file and write
}
....
}
the writeToFile() method can't be access for any other object create by a servlet. (just an example).
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's a bit inefficient. If you need to synchronize on the x.y Class object, and you know the name at compile time, a better way is

The .class notation incidates a class literal. I'd usually only use Class.forName() if the name is a variable, not known at compile time.
The other part of the question may be, is x.y.class the appropriate monitor object to use here? That, I can't say - depends on the problem. It often is the correct solution. It's worth noting that inside class x.y, this:

is exactly equivalent to:

Well, maybe not quite exactly, in that in past JDK editions the bytecodes generated in the latter case weren't quite as efficient. But that's just a failur of the compiler to optimize as much as it might - the two code segments are functionally exactly equivalent. So if you're interacting with other static methods or protecting static variables, then synchronizing on x.y.class it probably appropriate (if you don't want to synchronize the whole static method).
[ February 24, 2003: Message edited by: Jim Yingst ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!