How should I handle using this socket on multiple threads?

Hey there, I'm writing a SocketServer app to handle client communications and I've run into something I'm not sure how to handle. Currently, I have the main method create the SocketServer and start new threads whenever a client connects and keeps a list of clients that need to be updated with some info ("Stuff") (Basically a list, which when changed, each update will be sent to all clients on the list to be informed of updates). Each thread that's created when a new client connects is passed the instance of the 'PoolHandler' class, which is supposed to handle updates to the "Stuff" and send updates to any clients that need them. Currently, when a client adds itself to the list of users that need to be informed of updates on "Stuff", the thread that handles that client adds the client name and socket to a hashmap in 'PoolHandler' and anytime the "Stuff" is updated, 'PoolHandler' accesses the passed socket and sends the updates. I realize I'm probably not doing a very good job of explaining this, so I'll show my code:
public static void main(String[] args) throws IOException {
        final PoolHandler pool = new PoolHandler();
        ServerSocket serverSocket = null;
        while (listening) {
            new SNMultiServerThread(clients, pool, serverSocket.accept()).run();
public class SNMultiServerThread implements Runnable {
    public void run() {
        try {
            out = new BufferedOutputStream(socket.getOutputStream());
            in = new BufferedInputStream(socket.getInputStream());
            try {
                while ((read = in.read(input)) > 0) {
                    outputList = snp.process(input);
                    if (outputList != null && !outputList.isEmpty()) {
                        for (byte[] output : outputList) {
                            System.out.println("Transmitting: " +
                                    new String(output, 0, output.length));
                            synchronized(socket) {
                                out.write(output);
                                out.flush();
            } catch (SocketException e) {
public class PoolHandler {
    public PoolHandler() {
    private void updateClients(String update, String game, String team) throws IOException {
        if (update.equalsIgnoreCase("add")) {
            if (game.equalsIgnoreCase(CS)) {
                clientUpdateListDummy = clientUpdateListCs;
            } else {
            // The HashMap here is K=String, V=Socket
            for (Map.Entry<String, Socket> m : clientUpdateListDummy.entrySet()) {
                try {
                    out = new BufferedOutputStream(m.getValue().getOutputStream());
                    out.write(snp.prepareOutput(ADD_TEAM_REPLY, team));
                    out.flush();
                } catch (SocketException e) {
        } else if (update.equalsIgnoreCase("remove")) {
            if (game.equalsIgnoreCase(CS)) {
                clientUpdateListDummy = clientUpdateListCs;
            } else {
            // The HashMap here is K=String, V=Socket
            for (Map.Entry<String, Socket> m : clientUpdateListDummy.entrySet()) {
                try {
                    out = new BufferedOutputStream(m.getValue().getOutputStream());
                    synchronized(m.getValue()) { // synchronizing on the socket connected to the client, m.getValue()
                        out.write(snp.prepareOutput(REMOVE_TEAM_REPLY, team));
                        out.flush();
                } catch (SocketException e) {
}I attempted adding a synchronized block in the second for loop in PoolHandler, although i'm not sure if I need one at all or if that'll do the trick. The question, I guess, is should I be accessing the socket and then the outputstream for it from here (perhaps with the synchronized block that I added in the second for loop)? Or should I perhaps add a method in the Runnable class that transmits data via the socket and call that from PoolHandler? If I go with the second approach, can I simply pass the thread's name instead of the socket and use, say, m.getValue().transmitThisDataOverTheSocket(myData)? Thanks again, I hope this is clear. :)

So I've got another question about my code: will the PoolHandler class be responsive if used in the main() thread or do I need to implement Runnable in it and create a new thread also? If so, how should I go about it since I don't want PoolHandler to do anything other than keep track of clients and a few other client-related variables? Here's my main():
public static void main(String[] args) throws IOException {
        final PoolHandler pool = new PoolHandler();
        ServerSocket serverSocket = null;
        boolean listening = true;
        final int port = 4555;
        try {
            serverSocket = new ServerSocket(port);
        } catch (IOException e) {
            System.err.println("Couldn't listen on port: " + port);
            System.exit(-1);
        while (listening) {
            new SNThreadReader(pool, serverSocket.accept()).run();
        serverSocket.close();
    }

Similar Messages

  • My iphone is switched off as low batery and still viberates. how should i handle that problem?my iphone is switched off as low batery and still viberates. how should i handle that problem?

    my Iphoe is switched off and still viberates. how should i handle that problem?

    Try to set it up as new device and don't use the backup afterwards:
    How to back up your data and set up as a new device

  • How should I go about this dispute

    Hello everyone,
    So recently I've been trying to get an auto loan and kept getting denied. Finally asked DCU what the problem was and they said I had a repo under Capital One that was still being reported. That was back in 2009, I got the vehicle back and paid it off.
    Called COAF today and they acknowledged the resolution of the account but that they could not change how it was reporting. They were trying to get me to file a dispute through them though I refused and said I could do it myself through the 3 agencies. Is there any reason they were so hard pressed for me to file disputes through them? How should I go about this.

    Moetylerm wrote:
    Hello everyone,
    So recently I've been trying to get an auto loan and kept getting denied. Finally asked DCU what the problem was and they said I had a repo under Capital One that was still being reported. That was back in 2009, I got the vehicle back and paid it off.
    Called COAF today and they acknowledged the resolution of the account but that they could not change how it was reporting. They were trying to get me to file a dispute through them though I refused and said I could do it myself through the 3 agencies. Is there any reason they were so hard pressed for me to file disputes through them? How should I go about this.If this isnt updating monthly I suggest you just leave it alone and find another lender willing to work with you. You would only dispute it if it has factual errors in the way its reporting. If you dispute it if its not updating monthly when it updates after the dispute its going to cause a Fico score drop. If it is updating monthly now then you still would only dispute errors that are reporting but it wouldnt drop your Fico score anymore. DCU doesnt like other things they see in your CR is what I suspect since this actually is a redeemed repo and not one left unpaid.

  • I've signed up for a Students Single App Plan but I want to upgrade to a Students Complete plan, can/how should I go about this?

    I've signed up for a Students Single App Plan but I want to upgrade to a Students Complete plan, can/how should I go about this?
    It prompts me to upgrade to the complete plan, but not the complete students plan.

    I think you need Adobe contact information - http://helpx.adobe.com/contact.html

  • Relative path for Download directory folder.I created a firefox profile and i wanted to use this profile in multiple machines.I wanted to use a relative path for download directory with respect to the profile folder.I need this on Linux machines

    I have a use case where I need to use different download directories with different firefox profiles.I need to use this profiles in multiple linux machines.
    I need to have a relative path to my download directory with respect to the profile folder.
    Ex: I have a selenium test which opens a website and downloads it to my machine.I want this downloaded file to go into some specific folder relative to this profile folder.How do I do this??

    That is not a practically empty xinitrc - that file only needs one line: exec WM.  Other things are entirely optional, and some of them very useful, but I'd encourage you to stick with the simplest xinitrc that will do what you require.
    Is slim involved?  Probably.  That is the source of many problems.  But to start narrowing this down, I have 3 suggestions:
    1) temporarily (at least) change your inittab to default to runlevel 3 ... actually, is it currently set to 5 or 3? if it is currently 3 that would explain why slim doesn't start.
    2) at a tty in runlevel 3 use "xinit" instead of "startx".  Startx is fine most of the time, but it is essentially just a complex wrapper for xinit.  That complexity can often iadd useful functionality, but it *always* makes troubleshooting more difficult.  So for now just use a vanilla 'xinit'.
    3) remove dbus-launch from your exec line in xinitrc.  This is done by console-kit so it is redundant and potentially problematic.  Further BOTH of these are taken care of by slim, so I'd even suggest getting both a jump start on being ready for slim and simplifying troubleshooting by removing both of them.  Just make that line "exec openbox-session"
    Edit: adding one more:
    4) temporarily switch out openbox-session for openbox.  I suspect the reason feh's setting of the background is getting overridden is due to a script or setting in openbox's autostart settings - many of these are only invoked when "openbox-session" is called, while "openbox" starts *just* the window manager itself.
    Last edited by Trilby (2012-10-03 17:30:36)

  • Somehow my itunes started a new library and I lost my old library. Itunes will not allow me to sync new music to my ipod without deleting stored music from ipod. How can I start using this new library and sync the new music without losing existing music.

    Somehow my Itunes started a new music library and I lost the old library.  Itunes will not allow me to sync new music from my computer to my Ipod because it is now in a different library. Itunes wants to delete all my Ipod music before sync any new music. How do I work around this. I think this happened during Itunes Upates.

    Empty/corrupt library after upgrade/crash
    Hopefully it's not been too long since you last upgraded iTunes, in fact if you get an empty/incomplete library immediately after upgrading then with the following steps you shouldn't lose a thing or need to do any further housekeeping. In the Previous iTunes Libraries folder should be a number of dated iTunes Library files. Take the most recent of these and copy it into the iTunes folder. Rename iTunes Library.itl as iTunes Library (Corrupt).itl and then rename the restored file as iTunes Library.itl. Start iTunes. Should all be good, bar any recent additions to or deletions from your library.
    See iTunes Folder Watch for a tool to catch up with any changes since the backup file was created.
    When you get it all working make a backup!
    Should you be in the unfortunate position where you are no longer able to access your original library, or a backup of it, then see Recover your iTunes library from your iPod or iOS device.
    tt2

  • I have problems updating my app in the appstore. How should i update using itunes? Currently, i'm unable to use all of my apps.

    I have problems updating my apps in appstore for my IPad. How should i update it using itunes? I'm unable to see all the apps currently.

    Hallo. If all of your apps purchases from the same Apple ID, you can try to update them on iTunes, ways as below:
    iTunes 12 for Windows: Download previous purchases from the iTunes Store
    iTunes 12 for Mac: Download previous purchases from the iTunes Store
    Regards,
    Anson

  • HT201209 I have redemed my itunes card for $25.00. This amount shows next to my name. I cannot figure out how to purchase items using this amount. When I try to apply this, it tells me the promotion has been redeemed but I have not been able to buy anythi

    I have redeemed my itunes card for $25.00. This amount shows next to my account name. I chose songs from the itunes store and added to my wish list, but when I try to purchase these using my $25.00, it tells me this has already been redeemed. How do I buy songs and use my gift card to pay for them?

    The amount is already credited to your account. Purchase something and it will use this balance.

  • Flush=true, Should i be using this with jsp:forward...

    I had read up on this flush=true. SHould i be using it. Does it cause memory leaks with out it. I have read many articles and im confused. Can anyone explain this to me.
    Thanks

    anyone have any ideas on this. I have read through most of the forums and I am still unclear,
    Thanks again

  • Should i stop using this power supply??

    ok i know that i asked toooo much about my pc but forgive me i am sorry
    i searched for new Power suplly but the best is only 400 watt (+12---15a)
    so. should i use my one tell get an other or stop tell buy new one . is there any danger on my pc from using this week psu
    thanks
    my pc spec:
    pro:p4 3.2 1mb cash fsb 800
    board: Msi 865 PE NEO2 P SERIES
    VGA : HERCULES RADEON 8500
    SOUND : CREATIVE LIVE
    POWER SUPLY : 300W
    +3.3V 12A
    +12V 12A
    -12V 0.5A
    +5V 22A
    -5V 0.5A

    Let me repeat this one last time.
    You current PSU is too weak with only 300watts to spare and only 12A on +12v for a Prescott system. That's not the end. I've told you that a minimum of 18A ~ 20A is needed for any Prescott system and still you choose this 400watts with only 15A. This 15A on +12v PSU will not help out much nor long enough even if it can struggle for a few months, period at times.
    Get something like Antec 430watts TruePower or Enermax 465watts or above PSU that has met the requirements of a Power Hunger Prescott.
    Right now you situation is like trying to ask a person who's already starving from hunger to take 1 piece of bread per day and later told him that he can have a cup of water to go with the bread which isn't enough to kill the hunger as he needs more than what is provided.

  • How to send packet using tcp socket ?

    hi ,
    i want to using tcp socket to send data in ipv6 environment. but why the data transfer is less than ipv4 environment?
    socket = new Socket("2001:0238:0600::2", 1234);am i wrong ?

    bobby92 wrote:
    why the data transfer is less than ipv4 environment?What do you mean?
    >
    socket = new Socket("2001:0238:0600::2", 1234);am i wrong ?No idea, since I've no idea what you're asking.

  • How to proces the record in Table with multiple threads using Pl/Sql & Java

    I have a table containing millions of records in it; and numbers of records also keep on increasing because of a high speed process populating this table.
    I want to process this table using multiple threads of java. But the condition is that each records should process only once by any of the thread. And after processing I need to delete that record from the table.
    Here is what I am thinking. I will put the code to process the records in PL/SQL procedure and call it by multiple threads of Java to make the processing concurrent.
    Java Thread.1 }
    Java Thread.2 }
    .....................} -------------> PL/SQL Procedure to process and delete Records ------> <<<Table >>>
    Java Thread.n }
    But the problem is how can I restrict a record not to pick by another thread while processing(So it should not processed multiple times) ?
    I am very much familiar with PL/SQL code. Only issue I am facing is How to fetch/process/delete the record only once.
    I can change the structure of table to add any new column if needed.
    Thanks in advance.
    Edited by: abhisheak123 on Aug 2, 2009 11:29 PM

    Check if you can use the bucket logic in your PLSQL code..
    By bucket I mean if you can make multiple buckets of your data to be processed so that each bucket contains the different rows and then call the PLSQL process in parallel.
    Lets say there is a column create_date and processed_flag in your table.
    Your PLSQL code should take 2 parameters start_date and end_date.
    Now if you want to process data say between 01-Jan to 06-Jan, a wrapper program should first create 6 buckets each of one day and then call PLSQL proc in parallel for these 6 different buckets.
    Regards
    Arun

  • HT1688 I recently did an in game purchase for dh2014. they took the money off my itunes gift card but never gave me the purchase on the game.  I would like my money back or the purchase on the game please.  How should I handle this? i also wrote an email

    I am very upset with dh2014 I purchased an ingame product for more hunter bucks. they took the money out of my account and never game me the purchase on the game.  Is there anything I can do about this?

    Contact Apple support. We are not affiliated with Apple.
    You can do this by opening iTunes and going to your purchases. Apple will not give you your money back but they will enable download of the App again. You should also have the transaction number when you contact Apple.

  • How should I handle a file too large for DVD?

    I've created a 2-1/2 video of a play in FCE HD, utilizing two video tracks and three audio tracks in various spots, as well as some text transitions. With the title screens and scene index in iDVD, the movie comes in at about 8.5GB unless I switch to "Best Quality," in which case it's still 4.9GB (and doesn't look nearly as good as it should). So:
    1. Is there way to end up with a more managable file size from FCE without losing quality?
    2. If not, what's the best way to export a single FCE file to two movies (Acts I and II) to burn onto two DVDs?
    Thanks

    1) One way you could export content longer than 2 hours to DVD would be to go the dual layer route .. but you need a dual layer burner, and dual layer media. iDVD6 will handle this
    If you are limited to single layer, another option would be Compressor but that is not available with FCE, only DVD Studio Pro, part of the FCP Studio suite
    You could go the route of Toast 7 with Popcorn, but you would not get the fancy iDVD menus, themes, etc.
    Personally, I am not impressed with the quality of DVD content (single layer) over two hours by any method
    2) To split your project into two movies, create two new sequences and call them something like Part One and Part Two (gee, aren't I clever?) In you orginal sequence (Timeline) use In and Out points to define what the two parts will be ... so for Part One, set the In Point at the beginning of the timeline and find an appropriate point and hour or 90 minutes in and set an Out point.
    Open the Part One Sequence (the new one) From the Browser, drag your original Sequence (My Movie, whatever you called it) into Part One. Only the In to Out will go. You may want to put a Cross Dissolve at the end to fade to black. Maybe create a Part One Ends title there. Render everything. Set your chapter Markers. Export it and create an iDVD project from that movie
    Do the similar for Part Two

  • How should i go about this repair?

    Hey everyone, my 2007 macbook pro's lcd screen has failed to turn on, but the computer itself turns on - so i networked it to my friend's mac using firewire and my harddrive was all there so im able to save everything.
    so the problem is probably that i need to get a new graphics card. how do you suggest i go about this, will apple charge a lot for labour? should i take it to another computer store with better charges, or should i attempt to change it myself?
    thank you!

    There's a few things that may have failed with this computer:
    1) As you suggested, the graphics chipset might be toast. This means you have to replace the logic board, which can be costly no matter who repairs it.
    2) The display is broken. You need to get this computer connected to an external display and see if images show up properly. If so, the graphics chipset is OK and you can look into replacing the display, or part(s) of it.
    3) The inverter cable in the display has shorted out. This is least expensive part to replace.
    What I would do is make an appointment with a Genius bar at a store near you and go do some troubleshooting and/or have the folks there diagnose the computer. All of that shouldn't cost you anything but your time (and possibly the gas to get there!).
    ~Lyssa

Maybe you are looking for

  • New IPhone 5 is recognized by Windows but, not ITunes.

    IPhone 4S sync'd no problem with my laptop.  New IPhone 5 is recognized by Windows but, not ITunes.  ITunes has been updated, worked with Apple support for 2 hours this morning, still an unresolved problem.  Also, phone does sync on other computers.

  • Replication of activities(contact log) from CRM to R/3

    Hi, In our current project scenario we have requirement to replicate activites(contact log) from CRM to R/3.As standard SAP only replication of activites from R/3 to CRM, we need custom development to achieve replication from CRM to R/3. Can anyone g

  • How to create report in the following form?

    Hi All, how I am using FR studio for creating reports. I want to create a report which will show me accounts per entity,which means I want to keep the entity in the page dimension and accounts in the row dimension.The report should be done in such wa

  • Ranlib usage in Solaris 10 - Sparc vs i386

    Hi I have applications which use ranlib (though obseleted, but legacy software) as a part to create static libraries. Now it works fine on the SPARC Solaris 10, but when the same software is compiled in i386 Solaris 10, the static libraries are not f

  • Restoring view / Reproducing map

    Hi all, Is it possible to build restoring previous view in mapviewer application (developed using Mapviewer java API)? Here is some real time scenarios: Case 1 : User adds dynamic themes or dynamic features . Next he deletes these themes. Now if user