How can I use a Selector in a thread safe way?

Hello,
I'm using a server socket with a java.nio.channels.Selector contemporarily by 3 different threads (this number may change in the future).
From the javadoc: Selectors are themselves safe for use by multiple concurrent threads; their key sets, however, are not.
Following this advise, I wrote code in this way:
         List keys = new LinkedList(); //private key list for each thread
         while (true) {
          keys.clear();
          synchronized(selector) {
              int num = selector.select();
              if (num == 0)
               continue;
              Set selectedKeys = selector.selectedKeys();
              //I expected this code to produce disjoint key sets on each thread...
              keys.addAll(selectedKeys);
              selectedKeys.clear();
          Iterator it = keys.iterator();
          while (it.hasNext()) {
              SelectionKey key = (SelectionKey) it.next();
              if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
               Socket s = serverSocket.accept();
               SocketChannel sc = s.getChannel();
               sc.configureBlocking( false );
               sc.register( selector, SelectionKey.OP_READ );
              } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
//.....Unfortunately synchronizing on the selector didn't have the effect I expected. When another thread select()s, it sees the same key list as the other thread that select()ed previously. When control arrives to serverSocket.accept(), one thread goes ahead and the other two catch an IllegalBlockingModeException.
I'm not willing to handle this exception, the right thing to do is giving disjoint key sets to each thread. How can I achieve this goal?
Thanks in advance

A single thread won't be enough cause after reading data from the socket I do some processing on it that may take long.So despatch that processing to a separate thread.
Most of this processing is I/O boundI/O bound on the socket? or something else? If it's I/O bound on the socket that's even more of a reason to use a single thread.
Anyway I think I'll use a single thread with the selector, put incoming data in a queue and let other 2 or 3 threads read from it.Precisely. Ditto outbound data.
Thanks for your replies. But I'm still curious: why is a selector thread safe if it can't be used with multiple threads because of it's semantics?It can, but there are synchronization issues to overcome (with Selector.wakeup()), and generally the cost of solving these is much higher than the cost of a single-threaded selector solution with worker threads for the application processing.

Similar Messages

  • How can I use select() function in POSIX thread program.

    Hello
    Now I making a my own progam with POSIX thread in Solaris 8 Environment.
    But I have some trouble in POSIX thread.
    I saw that If use POSIX thread then use -D_POSIX_C_SOURCE=???L flag into compile options in
    Multithreaded Programming Guide.
    So I use that in my Makefile. But I can't compile my program.
    Now I found that if use POSIXC_SOURCE flag, cannot use timeval structure (defined in <sys/time.h>) in <sys/resource.h>.
    So compiling was stop into select() function. Because select() function use timeval structure.
    And fd_set structure(defined in <sys/select.h>) is same.
    How I solve this problem.
    Please help me.
    Thank you.

    Thanks so much for your helpful reply.
    Now I' ve already installed Adobe Creative Suite 6 Production Premium (Student Package), Extended included. But when I open Photoshop CS6, there' s still no 3D function in menu bar.
    Would you please tell me how to activate this function?
    Thanks,

  • Which List should be used, to remove in a thread safe way?

    Hello all,
    I plan to have a List, where n number of Threads will accessing the List.
    When two or more thread trying to remove an equals items from the List, only one of the thread will remove successfully (i,e, remove(Object o) will return true). The rest of the threads will realize remove(Object o) returns false
    I wish to achieve this. I know that I can achieve by using :
    Collections.synchronizedList(new ArrayList(...))However, I afraid having the synchronized block will slow down my execution speed. Is there other way, that I achieve the same objective with faster speed? For example, using CopyOnWriteArrayList?
    Thanks!

    Sorry,
    I said "badly" because it is synchornized by putting "synchronized" keyword on most of the methods prototypes.
    Which equals to synchronizing on "this".
    In my opinion, one problem of this implementation is that 2 calls to a get() method will be synchronized wherever they dont need to. (As get() does not modify the vector). [See Edit]
    One other is you can synchronize on the Vector's mutex (itself) outside of the Vector's code.
    And at last, as synchronizedList is not implemented by a Vector and is more recent than the Vector implementation...
    I guess they implemented it in another way for many good reasons...
    [Edit]
    As i can see in Collections, the synchronizedList is implemented in the same way.
    BUT, as the synchronized keyword is not in the method's prototype, we can expect the implementation to be changed a day...
    And vector is a kind of old object kept for backward compatibility i guess. (someone can confirm ?). ("As of the Java 2 platform v1.2, this class has been retrofitted to implement List, so that it becomes a part of Java's collection framework.")
    @KwangHooi
    You can write your own implementation of a List which will not synchronize on the same token for both read/write operations. (but, i guess it could be hard to avoid deadlocks)

  • How can I use 2 Apple IDs in Itunes? I have 2 IOS Devices. They each have there own AppleID. What is the proper way to sync both of them to Itunes?

    How can I use 2 Apple IDs in Itunes? I have 2 IOS Devices. They each have there own AppleID. What is the proper way to sync both of them to Itunes? I wanted my teenager's AppleID to be different from mine so that she couldn't charge stuff to my AppleID, therefore I created me another one. Now when I go to Sync either device, it tells me that this IOS device can only be synced with one AppleID. Then I get a message to erase it, not going to do that, lol. If I logout as one ID and login as the other, will it still retain all synced information on the PC from the first IOS device? If I can just log in out of the AppleID, then I have no problem doing that as long as the synced apps, music, etc stays there for both. I am not trying to copy from one to the other, just want to make sure I have a backup for the UhOh times. If logging in and out on the same PC of multiple AppleIDs is acceptible then I need to be able to authorize the PC for both devices. Thanks for the help. I am new to the iOS world.

    "Method Three
    Create a separate iTunes library for each device. Note:It is important that you make a new iTunes Library file. Do not justmake a copy of your existing iTunes Library file. If iTunes is open,quit it.
    This one may work. I searched and searched on the website for something like this, I guess I just didn't search correctly, lol. I will give this a try later. My daughter is not be back for a few weekends, therefore I will have to try the Method 3 when she comes back for the weekend again. "
    I forgot to mention that she has a PC at her house that she also syncs to. Would this cause a problem. I am already getting that pop up saying that the iPod is synced to another library (even though she is signed in with her Apple ID to iTunes) and gives the pop up to Cancel, Erase & Sync, or Transfer Purchases. My question arose because she clicked on "Erase & Sync" by mistake when she plugged the iPod to her PC the first time. When the iPod was purchased and setup, it was synced to my PC first. When she went home, she hooked it up to her PC and then she erased it by accident. I was able to restore all the missing stuff yesterday using my PC. However, even after doing that it still told me the next time I hooked it up last night that the iPod was currently synced with a different library. Hopefully, you can help me understand all this. She wants to sync her iPod and also backup her iPod at both places. Both PCs have been authorised. Thanks

  • How can i use my account without the billing info, as i do not have a credit card. and my shipping and billing info is under US. i'm in singapore. how do i change this?

    how can i use my account without the billing info, as i do not have a credit card. and my shipping and billing info is under US. i'm in singapore. how do i change this?

    If you are just visiting Singapore, then leave the account as it is. If you have moved there, then view your account using the iTunes app on a Mac or PC and change the country/region to your current location and address. If you do not have a bank card, you can fund your account using iTunes gift cards if available in Singapore.

  • How can I use one photo twice in a slideshow

    I am in iPhoto '11 9.4.3 making a slideshow to send to iDVD for my mother-in-laws funeral next Wednesday.
    How can I use this one particular photo of her several times in the slide show.
    I have tried copy/past and that does not seem to work.
    Thanx in advance

    I would just duplicate the picture several times and keep inserting duplicates ...

  • How can i use microsoft word on ipad 2

    how can i use the microsoft application on my ipad 2?

    The Pages app is also compatible with MS Word. Unlike some of the others mentioned, the document is actually stored on the iPad as opposed to 'the clouds'. Again, most of those mentioned are cut down versions of MS Word.
    Stand back and look at this constructively; do you need to regularly access to the document from more than one computer/device without the need to keep amending your document on your computer and sending it to your iPad? If so, Documente to Go etc may be the best choice.

  • How can I use the credit on my account instead of credit card to buy apps?

    I have a gift card credit on my account but when I want to buy an app it takes me to my credit card details. How can I use my credit on my account instead of credit card?

    You shouldn't have to put in a credit card, no, but from time to time the iTunes Store seems for some reason to try to insist on one. If just confirming your mailing address doesn't stop it from complaining, go here:
    http://www.apple.com/support/itunes/contact/
    and follow the instructions to report the issue to the iTunes Store.
    Regards.

  • How can i use one SQL statement to solve problem?

    How can i use one SQL statement to solve the question below?
    For a Table named A, there is a column named F(char type).
    Now select all the records where F like '%00' and update their F value to '%01'
    Just one SQL statement.Do not use PL/SQL block.
    How to do that?
    Thanks.

    What is the data volume for this table?
    Do you expect lots of rows to have '%00' as their value?
    Following two statements come to mind. Other experts would be able to provide better alternatives:
    If you have index on SUBSTR(f, 2):
    UPDATE A
    SET    f = SUBSTR(f,
                      1,
                      length(f) - 2) || '01'
    WHERE  substr(f,
                  -2) = '00';If most of the rows have pattern '%00':
    UPDATE A
    SET    f = SUBSTR(f,
                      1,
                      length(f) - 2) ||
               DECODE(SUBSTR(f,
                             -2),
                      '00',
                      '01',
                      SUBSTR(f,
                             -2));

  • How can i use one iCloud Photostream on 2 devices?

    Due to a bug (or feature) on iOS 8 i can't use the same icloud id on 2 iphones:
    https://discussions.apple.com/thread/6536998
    So how can i use ONE iCloud Photostream then on 2 devices?
    Also, on OSX i can define only one Photostream.
    So, how do you import pictures from 2 streams into iPhoto?
    Familyshare is not usefull as the pictures are not in Original-Filesize!

    Hi ..
    Yes. " iPhone 6 or 6 Plus.  iPad Air 2  or  iPad mini 3"
    Set up and use Apple Pay

  • HT204053 Dear Support Team, every time i tried to logon Icloud its gives me wrong user name or password and at the end it show me error " This Apple ID is valid but is not an ICloud Account" then how can i use one account for same Apple ID and ICloud???

    Dear Support Team,
    Every time i tried to logon Icloud its gives me wrong user name or password and at the end it show me error " This Apple ID is valid but is not an ICloud Account" then how can i use one account for same Apple ID and ICloud?
    Thanks

    It is not possible to create a new iCloud account using a Windows machine. You must create the account using a Mac (10.7.5 or more) or an IOS device (iPhone etc). Once that is done you can sign into and use the account on your Windows machine.

  • How can I use same account in 2 iphone with diff contact list?

    how can I use same account number but other all totally diff such as contact list, application, everything ..... I found that it's bad on IOS5.
    when I used IOS4 .. old verison, I can keep my phone in diff data. Afte upgrade IOS 5, it's bad. Even take photo, it can not focus zoom in and out.

    how can I use same account number but other all totally diff such as contact list, application, everything ..... I found that it's bad on IOS5.
    when I used IOS4 .. old verison, I can keep my phone in diff data. Afte upgrade IOS 5, it's bad. Even take photo, it can not focus zoom in and out.

  • How can i use my ipod on 2 computers without deleting my music

    how can i use my ipod on 2 computers without deleting my music on ipod?

    See here: Using iPhone, iPad, or iPod with multiple computers
    B-rock

  • How can I use home sharing between our iphones (create playlists from both accounts at once)

    How can I use home sharing between our iphones, so that we can create playlists with songs from both of our libraries?  We share a Macbook Pro (separate accounts) and each have the new iphone, but when I have my iphone and try to create a new playlist, I can only grab songs from one account.  Is there a way to create a playlist using both accounts since we are sharing?
    Does it have to be created within iTunes first on our Mac?

    The short answer: because Home Sharing isn't designed for sharing apps, and apps aren't designed to be shared.
    The longer answer:  Think of it like this...
    You download some music in iTunes.  With Home Sharing, another user can listen to it by streaming it over the network.  But the data itself is on your computer.  If you turn off the computer or take it off the network, the other user can't access it.
    But if you send another user the app, they aren't just streaming the data- they installed it on their iOS device.  Because they weren't the one that purchased it, such a transfer could easily be considered "piracy" or "stealing," and nobody likes that (least of all, Apple). 
    When iTunes sees this app, it obviously recognized it, as if saying, "Hey, how did you get this app on your device, if I have no record of you purchasing/downloading it from the iTunes store?"
    post edited to correct spelling errors

  • How can I use the old Apple TV with new iTunes?  It tells me to input a code in iTunes but iTunes no longer has a spot to input this code to allow sync.  I can access the iTunes Store fine, just none of my Library

    How can I use the old Apple TV with new iTunes?  It tells me to input a code in iTunes but iTunes no longer has a spot to input this code to allow sync.  I can access the iTunes Store fine, just none of my Library

    read this
    https://discussions.apple.com/message/20429789#20429789

Maybe you are looking for