Path: csiph.com!usenet.pasdenom.info!aioe.org!eternal-september.org!feeder.eternal-september.org!mx04.eternal-september.org!.POSTED!not-for-mail From: Knute Johnson Newsgroups: comp.lang.java.programmer Subject: Re: Strange Socket problem Date: Fri, 02 Mar 2012 17:18:04 -0800 Organization: A noiseless patient Spider Lines: 54 Message-ID: References: <4f512b27$0$26687$65785112@news.neostrada.pl> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Sat, 3 Mar 2012 01:18:04 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="mz/LDSJwiWnk3Jnnqg7x+Q"; logging-data="13508"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18tr14GFsjr/1i5pysoCEbP" User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:10.0.2) Gecko/20120216 Thunderbird/10.0.2 In-Reply-To: Cancel-Lock: sha1:PZf8ogxRHw84O5pWj9P8osdxjtM= Xref: csiph.com comp.lang.java.programmer:12611 On 3/2/2012 4:00 PM, Lew wrote: > Knute Johnson wrote: >> The volatiles exist because the methods that access them can be called >> from >> other threads. I could have synchronized the start() stop() methods >> but not >> easily the socket variable in the run() method. I thought it was >> cleaner to >> just use volatile. > > I see a problem right there. > >> public void disconnect() { >> if (isConnected()) >> if (socket != null) >> try { >> socket.close(); >> } catch (IOException ioe) { >> ioe.printStackTrace(); >> } >> } > > Since these are controlled by separate synchronization (different > 'volatile' variables) there's a race condition trying to work with both > at once. I don't think so. > Also, 'socket' can become 'null' between the check for not 'null' and > the 'close()' call. Only if I set it to null and I don't. That is there so that if the Socket doesn't make the first connection when disconnect() is called that I won't get a NPE. > You need to synchronize with 'synchronized' or other strong mechanism. I don't think so and here's why; isConnected only gets modified by one thread and read by another, socket is only modified by one thread and read by another. In the disconnect() method, as soon as isConnected() is called, isConnected the volatile variable is read and that would make socket current even if it weren't volatile which it is but I didn't want to rely on side effects in case I changed code somewhere. Anyway, disconnect() isn't getting called in this situation so it's not causing my problem. I really appreciate everybody looking at this. I've got a couple of ideas of where to code some traps and I'll have to put those in one night and see what happens. -- Knute Johnson