Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / February 2007

Tip: Looking for answers? Try searching our database.

Thread safe IO?

Thread view: 
Mark Space - 30 Jan 2007 02:29 GMT
Hi all.  I'm trying to write some basic network communication in Java,
and I've got a problem I can't resolve.  The code below compiles and
works correctly (in so far as I'm able to test), but I fear there may be
some hideous issues lying just beneath the surface.

The basic idea below is a chat server.  This illustrates my issue well
enough, although later I might be doing stuff beside just using a
PrintWriter for output.  The class Main starts by initializing a list of
connections to null, and then waiting for ServerSocket connections on
port 24674.  When it gets one, it creates a new instance of itself (this
initializes the "client" variable) and then spawns an new thread.

Once in the new thread (in "run") I create the readers and writers I
need, then I add the PrintWriter to the linked list "connections."
There's only one linked list, it's a static variable shared by all
threads.  Then the thread waits for input, and when it gets a line from
the socket, it iterates over the linked list "connections," sending it's
out to each PrintWriter there.

This works fine.  I can create multiple connections to this application
with telnet, and see any input I type echoed in each window.

What I'm concerned about is that this doesn't really seem like regular
use of the socket.  Normally I think one thread would first read, then
write to a socket, or perhaps vice-versa.  Here, for each socket, most
times one thread will be blocked on the input, while another thread is
stuffing bytes down it's output.  Plus if a thread isn't blocked (is
actively collecting bytes or something) and some other thread is writing
bytes one the same socket, well, I have no idea what'll happen.

I can't find any documentation on this.  Socket objects, and their IO
objects, aren't listed as being inherently thread safe.  I'm not
accessing a single object twice, but there could be stuff going on under
the hood that makes this not safe.

Any one got some docs where thread safety might be touched on in greater
detail for Socket based IO?  Any help is much appreciated.

Cut code below this line:
---------8<--------------8<----------

package chattest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class Main implements Runnable
{
    private static List connections;
    Socket client;

    public Main( Socket client ) {
    this.client = client;
    }

    public static void main(String[] args) throws IOException
    {
    connections = Collections.synchronizedList( new LinkedList() );
    ServerSocket ss = new ServerSocket( 24674 );
    while( true )
       new Thread( new Main( ss.accept())).start();   
    }

    public void run() {
    try {
       BufferedReader in = new BufferedReader( new InputStreamReader(
client.getInputStream()));
       OutputStream out = client.getOutputStream();
       PrintWriter pout = new PrintWriter( new OutputStreamWriter( out),
true );
       connections.add( pout );
       while( true ) {
        String chat = in.readLine();
        synchronized( connections ) {
           PrintWriter temp_pout;
           Iterator itor = connections.iterator();
           while( itor.hasNext() ) {
            temp_pout = (PrintWriter) itor.next();
            temp_pout.println( chat );
           }
        }
       }
    }
    catch (IOException ex) {
       ex.printStackTrace();
    }
    }
}
Esmond Pitt - 31 Jan 2007 00:59 GMT
> The basic idea below is a chat server.  This illustrates my issue well
> enough, although later I might be doing stuff beside just using a
> PrintWriter for output.

You do realize that PrintWriter swallows all exceptions so you'll never
know about write failures?

> Then the thread waits for input, and when it gets a line from
> the socket, it iterates over the linked list "connections," sending it's
> out to each PrintWriter there.

Bad idea. If any client isn't reading for any reason, writing to it will
 eventually block, which will block this entire process. You need a
write thread per client. Or NIO.

> What I'm concerned about is that this doesn't really seem like regular
> use of the socket.  Normally I think one thread would first read, then
> write to a socket, or perhaps vice-versa.  Here, for each socket, most
> times one thread will be blocked on the input, while another thread is
> stuffing bytes down it's output.

Agreed, see above.

>  Plus if a thread isn't blocked (is
> actively collecting bytes or something) and some other thread is writing
> bytes one the same socket, well, I have no idea what'll happen.

That part works OK. TCP gives you a full-duplex connection, and Socket
and its streams are thread-safe. You can even read and/or write with
multiple threads at the same time, but there are no guarantees about how
the data will be interleaved.
Mark Space - 01 Feb 2007 00:27 GMT
Thanks for the replies!

> You do realize that PrintWriter swallows all exceptions so you'll never
> know about write failures?

Nope, didn't know this.  I'll have to check this out more...

> Bad idea. If any client isn't reading for any reason, writing to it will
>  eventually block, which will block this entire process. You need a
> write thread per client. Or NIO.

I guess if one client is writing a lot, and not checking it's input,
then which ever server thread is writing to that client will eventually
block.  Then all server threads will eventually block on that thread
which never relinquishes its lock.

It's not likely, given the nature of the app, but I see your point.  I'm
probably going to be switching to passing (data) objects across a socket
soon, and the possibility of one object with a lot of data getting
stuffed in the socket is much higher.  Data objects much larger than a
buffer or a window size are quite likely.  NIO it is.

> That part works OK. TCP gives you a full-duplex connection, and Socket
> and its streams are thread-safe. You can even read and/or write with
> multiple threads at the same time, but there are no guarantees about how
> the data will be interleaved.

This was my real question.  Is Java full duplex also for its Socket API?
 The answer appears to be yes.  So the API part is ok, but for design
issues I'll be using NIO or some form of non-blocking IO.

Thanks again! ^_^


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.