Re: Simple(?) synchronized() block question
- From: Thomas Hawtin <usenet@xxxxxxxxxxxxxxxxx>
- Date: Fri, 30 Jun 2006 16:43:50 +0100
noident@xxxxxxxxxxx wrote:
public class Foo extends Thread
Extending Thread is almost always a bad idea. If your book tells you to do that, burn it.
{
private String s;
public Foo(String ss) { s = ss; }
public void run()
{
synchronized(s) // changing this line to 'synchronized(this)' fixes
the problem
Using a client supplied String for a lock isn't a great idea. The String may be shared with the rest of the code in the JRE.
A handy little trick is to declare a nested or local class called Lock with an empty body. The full name of classes are shown if you use ctrl-\, ctrl-break, jstack or similar. A custom class name will help you identify locks.
{
try
{
wait();
Even if the Thread was the right object to wait on, Thread is a bad choice of lock. In Sun JVMs, Thread uses itself as a lock for internal operations. Attempting to lock it yourself may give strange results.
You need to be careful what you synchronise on. An easy mistake is to lock on an outer class instance, and then within in an inner class lock on the inner class instance because this is different.
}
catch(InterruptedException e)
{
System.err.println(e);
System.exit(1);
Seems a little extreme...
}
}
}
public static void main(String[] args)
{
new Foo("abc").start();
}
}
Tom Hawtin
--
Unemployed English Java programmer
http://jroller.com/page/tackline/
.
- References:
- Simple(?) synchronized() block question
- From: noident
- Simple(?) synchronized() block question
- Prev by Date: Re: Encoding conversion from UTF to ISO-8859-7
- Next by Date: Re: Detecting clsoed socket on OutputStream.Write
- Previous by thread: Re: Simple(?) synchronized() block question
- Next by thread: Wanna play????
- Index(es):
Relevant Pages
|