Both blocking and non-blocking io

I'm wondering if this scenario is possible with the new nio classes:
I have a caching server. Clients connect to the server and occasionally send requests for objects. I'd like to use the nio non-blocking APIs to detect that there is a read pending on a socket. However, once I detect this, I'd like to go into a blocking loop to process the request. After this done, I'd like to go back into non-blocking mode and wait for another request.
It seems like this should be possible but the (woefully lacking) documentation isn't clear. Neither is the source code, apparently.
I've got a test case working but I was hoping someone could validate for me that this is support behavior. It's done by waiting for the isReadable() key then calling socket.keyFor(selector).cancel(); and then socket.configureBlocking(true); The reads are then done in blocking mode until the request is done and then the socket is registered with the selector again.
Thanks for any help on this.

I have to ask why you would want to mix blocking and non-blocking I/O.
The only reason you would (IMHO) want to use non-blocking I/O is in a highly concurrent system, to increase the maximum load a system can handle.
The main reason you would want to use blocking I/O rather than non-blocking I/O would be to minimise the latency for a single request.
Unfortunately, the two don't seem to mix together very well... by switching a thread to blocking, you decrease the latency for a single request, but increase latency for the other requests due to reduced resources available. Similarly, by switching to blocking, you are requiring a dedicated thread for that request, so limiting the number of concurrent requests that can be serviced.
That is, it seems to me that using both blocking and non-blocking I/O introduces the weaknesses of both into the system, without gaining much of the benefits of either.
The above aside, the method you gave looks like it would work as you expect, depending on what you are doing with thread creation/delegation. Did your test case work as expected?

Similar Messages

  • Blocking and non-blocking workflows

    How to specify a workflow to be blocking and non-blocking?
    Regards,
    Miguel

    When registering the custom workflow from Application Server Control (Enterprise Manager Web Site), you will see an option to specify whether the workflow is blocking:
    Application Server Control > Content > Custom Workflows
    Register Workflow
    * Name  
      Description  
    * Launch Event  
    * Cancel Event  
      Blocking
      Approvers Required

  • SQL Developer blocking vs non-blocking

    Hi,
    Is there a way in SQL Developer 3.0 to have a non-blocking SQL call? In Oracle Forms we can choose between blocking and non-blocking SQL Net connections to the database. Does SQL Developer have the same capability? If so where exactly are those options hidden in the preferences menus?
    Annoyed,
    ScottK
    Edited by: ScottK on Jun 1, 2011 11:20 AM

    Hi ScottK,
    SQLDeveloper locks access to individual connections when they are in use, if you want to simulate
    some aspects of non blocking behaviour you can use other connections.
    The following features might help:
    Use a different connection name back to the same schema in your database - it will be treated as an independent connection and 'blocking' on this connection will not affect your other connections.
    This can be achieved temporarily in the worksheet by:
    ctrl shift n
    which creates a worksheet with new connection independent of your existing worksheet connection
    though connected to the same schema and database.
    -Turloch
    SQLDeveloper team

  • Reg Price block and Qty block in MM Invoice docs Tolerence Keys adjustment

    Hi Friends,
    Related to MM Invoice documents gets blocked with Price block and Qty block,based on this FI doc also gets blocked with Payment block indicator"R".As per Std SAP we can remove these blocks thru MRBR. Right now my users are asking not required to remove these blocks with MRBR Tcode.
    So i checked the Tolerence Limits defined for the co code and Tolerence keys.
    As per my understanding Tolerence Keys "PP-Price variance",  "DQ-Exceed amount: quantity variance" need to adjust with upper llimits and Lower Limits.
    here i can see Upper and Lower check limit Tolerance limit 5.00%  for  Tolerence Key "PP-Price variance"
    Tolerence limit 0.01%  for  Tolerence key "DQ-Exceed amount: quantity :quantity variance         
    Instead of changing the Tolerence Limits can i select the DO NOT CHECK Radio button for the bothe Price and Qty block.
    If i selected the DO NOT check button what will happen,how it works.
    How i can maintain the Tolerence keys,is there any other Tolerence keys also need to maintain.  
    Please suggest me with your valuable inputs.  
    Brgds,
    RK
    Edited by: RK.SAP on Nov 17, 2010 7:02 AM

    hi,
    If you do not want to check the Invoice for tolerance keys like quantity variance and price varaince then tick on don't check .In this case system will not block any invoice and invoice will post Automatically without any error.
    Please check other tolerance keys in SPRO: OMR6
    One more blocking is defined in the vendor master also under payment transactions accounting screen.There you are defining the tolerance group for Invoice Verification.
    Regards,
    Amit

  • UTL_TCP (blocking or non-blocking sockets mode)

    Hi for All,
    Please, someone knows if the UTL_TCP using blocking or non-blocking sockets mode? I did a search but can not find this information.
    Regards,

    Blocking only occurs when you attempt to read from the socket and there's no data to read. (in which case, the time out setting applies if specified)
    This is however not that robust in my experience. UTL_TCP provides a peek method (returns byte size of socket buffer) that tells you whether or not there is data for that socket. This enables you to verify that you read on that socket will not be a blocking call.
    I prefer using this method, as dealing with a timeout approach results in run-time behaviour issues (either a call waiting too long, or a call timing out too quickly).

  • Data source for application using both pooled and non pooled connections

    Hi guys.
    I am integrating Oracle's connection pooling into an existing application that had formerly used dbConnectionBroker. It looks like this task should be quite straightforward. However, for consistency, I would also like to replace other Connection logic within the application to use Oracle classes. This will involve using OracleDataSource to obtain a Connection object. ( without pooling ).
    So in this case, the application will use both pooled and non pooled Oracle connections. They will be connecting to the same database. The question I have is in regard to the use of data-sources.xml.
    Are there any special considerations for the required attribute values within data-sources.xml under this scenario ?
    Help will be greatly appreciated.
    Regards.
    Steve.

    Hi Steve -
    It should be feasible for you to define a single datasource using multiple location entries to indicate what sort of pooling behaviour you wish to use.
    If you lookup and use the "location" attribute, you will receive a javax.sql.DataSource object which will not provide connection pooling.
    If you lookup and use the "ejb-location" attribute you will receive a DataSource object that will support connection pooling operations.
    Note that this is using the emulated datasource approach, and transaction support is limited to a single resource (one database) for these datasources - you won't get 2PC support for transactions.
    If you need a transaction to span two separate resources (ie two databases in same tx) then you will need to use the non-emulated datasource approach.
    There is a chapter in the J2EE Services Guide which describes the datasource model we have with OC4J. This might provide you with some more useful information. See Chapter 11 - http://otn.oracle.com/docs/products/ias/doc_library/903doc_otn/generic.903/a97690/ds3.htm#1004903
    cheers
    -steve-

  • Does table MCHB (batch stocks) contain both valuated and non valuated stock

    Hello
    Does table MCHB (batch stocks) contain both valuated and non valuated stock?
    Is it possible that material has both valuated and non valuated stock for the same plant and storage location?
    Thanks

    Hi ,
    Most of your queries has been answered by Jurgen.
    1)Does valuated or non valuated is linked with valuation type? yes ..if the material is valuated then only there is valuation type.It is used for split valuation .
    2)Where can I see whether material is valuated on plant or not?
    to check the valuation level IMG >Enterprise Structure>Definition>Logistics - General>Define valuation level
    and to check value and quantity updation at plant level check
    IMG >Logistics - General>Material Master>Basic Settings>Material Types-->Define Attributes of Material Types
    3)Case1
    I want material A to be valuated at the plant without split valuation
    Case
    I want material B to have 0 value at plant
    go as Jurgen has recommanded in the previous post . for material B used different material type which is not valuated at that plant .
    Regards,
    Anupam

  • Both excisable and non-excisable items are in a same location (Warehouse)

    What will be best solution for the client (of SAP B1 2007 B PL7), those who have both excisable and non-excisable items are in a same location (Warehouse)...??...Is there any need to create two warehouses?... but how will be the excisable setting???

    Hii Das
    The best solution would be only to create two diffrent ware house for excisable and non excisable
    , to avoid unneccesary confusions, and to stay away from un avoidable errors
    Thanks
    Rizz

  • Set Posting block and Purchasing block automatically upon vendor creation

    Hi.
    I have a requirement to automatically set the purchasing block and posting block to 'X' upon creation of vendor master. I have seen a user exit to do this but then I can't seem to find a way to set the SPERM field to 'X'.
    Please help. THanks.

    Transaction FIBF start the event manager.
    on menu: environment->info system (P/S) and then execute: it will be displayed all possible events.
    between event 1410 and 1460, you will find all events about vendor.
    click on documentation, it will tell you when the event is reached and what you can do.
    After you have choose an event, you must create a function module, copying it from the sample function module of the event.
    Once you have created your own funcion module, you should go to:
    FIBF->SETTINGS->P/S MODULES.
    This part of customization is not very clear to me, i've never done by myself. Anyway, here you associate at the businness event the function module you have created.
    Sorry for not beeing exaustive, hope anyway could be help you.
    Regards
    Andrea

  • Problem in Execute query on non-database block and database block together

    Hi All,
    In my form,i have
    1. First block is Non-database block with one non-database item.
    2. Second and third blocks are database blocks.
    Now the problem is that i want to perform execute-query for all the blocks.
    If the cursor is on the non-database item of 1st block and i clicks on the "Enter-query" then i am getting message " This function can not be performed here".
    If i click on the item of the database block and then clicks on the "Enter-query" and then "execute-query" it's working fine.
    But i don't want to do in this way.
    My cursor will be on the First block only and then it should perform execute-query.
    I am using this non-database item to copy value of this item to the item of the database block item.
    I think i make you understand about my problem.
    I am using forms 10g on Window xp.
    Please help me.

    Hi!
    Simply create a enter-query trigger on the non-database-block:
    begin
    go_block ( 'database_block' );
    enter_query;
    end;If your search criteria is in the non-database-item in the first block,
    you actually do not need the enter_query build-in.
    Just create a execute-query trigger on the first block like:
    begin
    go_block ( 'database_block' );
    execute_query;
    go_item ( :System.trigger_item );
    end;And in a pre-query trigger on the database-block copy the
    value of your seach item into the item you want to search for.
    Regards

  • OCCI and non-blocking

    I'd like to use the OCCI interface in a non-blocking mode. Does anyone have any experience with this? Looks like I need to use a combo of OCI and OCCI calls to set the OCI_HTYPE_SERVER handle with the OCI_ATTR_NONBLOCKING MODE. However, my stmt->executeQuery() method seems to be throwing an exceptions, which I would have though would have been the OCI_STILL_EXECUTING error, but it's not. The exeception is an "ORA-32103 error from OCI call". If I continue to do another stmt->executeQuery(), I eventually get an access exception.
    Anyone have any code snippets using OCCI in non-blocking mode?

    I use threads. ACE/TAO to be precise.
    I have singleton class that manages the Oracle environment and connection as well as being a statement
    factory.
    Just have a thread perform your stmt->executeXXX() method and you will not need to worry about non-blocking.
    That's how I do it and it works well.

  • How to select only layers that are both, visible and not blocked in photoshop cc?

    I used to do it in photoshop CS6 without any configuration, but now I can select only "not blocked" or "visible" layers? Can't I select both?

    We will need to reformat your EXT, but it will then work on both Mac and Win
    Connect the drive to your Mac, open disk utility
    Go to the partiton tab and select '1' ... format should be ExFAT ... in options select MBR
    Format the drive
    It should now work on both OSs; report back

  • Chaining WritableByteChannels and non-blocking I/O?

    Hello all,
    Suppose I want to implement a data transformation algorithm that works in chunks of say 4 bytes.
    The algorithm would hook into existing I/O paradigms for writing and reading data.
    Ignoring the transformation algorithm for now (it is actually irrelevant for my question), let's just I need to buffer data in 4-byte chunks.
    Since I want to make as little assumptions as possible about the decorated channel, BufferingWritableByteChannel needs to work channels in blocking and in non-blocking mode.
    When the decorated channel is in non-blocking mode, BuffereingWritableByteChannel may behave as in non-blocking mode itself, which is fine by me.
    However the problem is with the residual bytes: they do not get written until the close() method is called.
    I have implemented the close() method to be blocking (the while loop with the ugly yield() calls), so even when the decorated channel is in non-blocking mode everything will get written properly.
    However, writing potentially blocking calls (busy loops) in close() methods seems like a bad idea...
    So the question is:
    Is there a better way of doing this?
    Can I avoid having to write busy loops?
    package nio;
    import java.io.IOException;
    import java.nio.ByteBuffer;
    import java.nio.channels.WritableByteChannel;
    import static nio.ChannelUtils.*;
    public class BufferingWritableByteChannel implements WritableByteChannel {
      private final WritableByteChannel decoratedChannel;
      private final ByteBuffer buffer = ByteBuffer.allocate(4);
      private boolean buffering = true;
      public BufferingWritableByteChannel(WritableByteChannel decoratedChannel) {
        this.decoratedChannel = decoratedChannel;
      public synchronized void close() throws IOException {
        if (buffering) {
          buffer.flip();
        writeBlockingly(decoratedChannel, buffer);
        buffer.clear();
        decoratedChannel.close();
      public synchronized boolean isOpen() {
        return decoratedChannel.isOpen();
      public synchronized int write(ByteBuffer input) throws IOException {
        int bytesWritten = 0;
        if (!buffering) {
          decoratedChannel.write(buffer);
          if (buffer.hasRemaining()) { // May happen when decorated channel in non-blocking mode
            return bytesWritten;
          buffer.clear();
          buffering = true;
        while (input.hasRemaining()) {
          bytesWritten += putAsMuchAsPossible(input, buffer);
          if (!buffer.hasRemaining()) {
            buffer.flip();
            decoratedChannel.write(buffer);
            if (buffer.hasRemaining()) { // May happen when decorated channel in non-blocking mode
              buffering = false;
              return bytesWritten;
            buffer.clear();
        return bytesWritten;
    package nio;
    import java.io.IOException;
    import java.nio.BufferOverflowException;
    import java.nio.ByteBuffer;
    import java.nio.channels.WritableByteChannel;
    public class ChannelUtils {
      private ChannelUtils() {
       * Blockingly writes data to a channel, even if the channel is in non-blocking mode.
      public static final int writeBlockingly(WritableByteChannel channel, ByteBuffer buffer) throws IOException {
        int bytesWritten = 0;
        boolean yield = false;
        while (buffer.hasRemaining()) {
          bytesWritten += channel.write(buffer);
          if (yield)
            Thread.yield();
          else
            yield = true;
        return bytesWritten;
       * Puts as much bytes as possible from an input buffer into an output buffer, avoiding {@link BufferOverflowException}.
      public static final int putAsMuchAsPossible(ByteBuffer input, ByteBuffer output) {
        int bytesWritten = Math.min(input.remaining(), output.remaining());
        ByteBuffer inputSlice = input.slice();
        inputSlice.limit(inputSlice.position() + bytesWritten);
        output.put(inputSlice);
        input.position(input.position() + bytesWritten);
        return bytesWritten;
    }

    Hello all,
    Suppose I want to implement a data transformation algorithm that works in chunks of say 4 bytes.
    The algorithm would hook into existing I/O paradigms for writing and reading data.
    Ignoring the transformation algorithm for now (it is actually irrelevant for my question), let's just I need to buffer data in 4-byte chunks.
    Since I want to make as little assumptions as possible about the decorated channel, BufferingWritableByteChannel needs to work channels in blocking and in non-blocking mode.
    When the decorated channel is in non-blocking mode, BuffereingWritableByteChannel may behave as in non-blocking mode itself, which is fine by me.
    However the problem is with the residual bytes: they do not get written until the close() method is called.
    I have implemented the close() method to be blocking (the while loop with the ugly yield() calls), so even when the decorated channel is in non-blocking mode everything will get written properly.
    However, writing potentially blocking calls (busy loops) in close() methods seems like a bad idea...
    So the question is:
    Is there a better way of doing this?
    Can I avoid having to write busy loops?
    package nio;
    import java.io.IOException;
    import java.nio.ByteBuffer;
    import java.nio.channels.WritableByteChannel;
    import static nio.ChannelUtils.*;
    public class BufferingWritableByteChannel implements WritableByteChannel {
      private final WritableByteChannel decoratedChannel;
      private final ByteBuffer buffer = ByteBuffer.allocate(4);
      private boolean buffering = true;
      public BufferingWritableByteChannel(WritableByteChannel decoratedChannel) {
        this.decoratedChannel = decoratedChannel;
      public synchronized void close() throws IOException {
        if (buffering) {
          buffer.flip();
        writeBlockingly(decoratedChannel, buffer);
        buffer.clear();
        decoratedChannel.close();
      public synchronized boolean isOpen() {
        return decoratedChannel.isOpen();
      public synchronized int write(ByteBuffer input) throws IOException {
        int bytesWritten = 0;
        if (!buffering) {
          decoratedChannel.write(buffer);
          if (buffer.hasRemaining()) { // May happen when decorated channel in non-blocking mode
            return bytesWritten;
          buffer.clear();
          buffering = true;
        while (input.hasRemaining()) {
          bytesWritten += putAsMuchAsPossible(input, buffer);
          if (!buffer.hasRemaining()) {
            buffer.flip();
            decoratedChannel.write(buffer);
            if (buffer.hasRemaining()) { // May happen when decorated channel in non-blocking mode
              buffering = false;
              return bytesWritten;
            buffer.clear();
        return bytesWritten;
    package nio;
    import java.io.IOException;
    import java.nio.BufferOverflowException;
    import java.nio.ByteBuffer;
    import java.nio.channels.WritableByteChannel;
    public class ChannelUtils {
      private ChannelUtils() {
       * Blockingly writes data to a channel, even if the channel is in non-blocking mode.
      public static final int writeBlockingly(WritableByteChannel channel, ByteBuffer buffer) throws IOException {
        int bytesWritten = 0;
        boolean yield = false;
        while (buffer.hasRemaining()) {
          bytesWritten += channel.write(buffer);
          if (yield)
            Thread.yield();
          else
            yield = true;
        return bytesWritten;
       * Puts as much bytes as possible from an input buffer into an output buffer, avoiding {@link BufferOverflowException}.
      public static final int putAsMuchAsPossible(ByteBuffer input, ByteBuffer output) {
        int bytesWritten = Math.min(input.remaining(), output.remaining());
        ByteBuffer inputSlice = input.slice();
        inputSlice.limit(inputSlice.position() + bytesWritten);
        output.put(inputSlice);
        input.position(input.position() + bytesWritten);
        return bytesWritten;
    }

  • Troubles with timeout using java.nio.channels and non-blocking sockets

    Hello.
    I have a server application that employs java.nio.channels with non-blocking sockets.
    The server waits for connections. The client should connect and be first in sending data.
    Timeouts are significant! If client exceeds the allowed time to send data, the server should break the connection.
    The huge trouble I've discovered that I cannot control the timeout when client connects but remains silent.
    My code looks as follows:
    <pre>
    Selector oSel;
    SocketChannel oSockChan;
    Socket oSock;
    SelectionKey oSelKey;
    Iterator<SelectionKey> oItSelKeys;
    int iCurrState, iMask, iCount;
    iCurrState = INT_SERVER_WORKING;
    iMask = SelectionKey.OP_ACCEPT | SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE;
    while ( iCurrState == INT_SERVER_WORKING )
    try
    *// retrieving next action*
    iCount = oSel.select();
    if ( iCount > 0 )
    oItSelKeys = oSel.selectedKeys().iterator();
    while ( oItSelKeys.hasNext() )
    oSelKey = oItSelKeys.next();
    oItSelKeys.remove();
    if ( oSelKey.isValid() )
    switch ( oSelKey.readyOps() & iMask ) {
    case SelectionKey.OP_ACCEPT :
    oSockChan = oSSockChan.accept();
    oSockChan.configureBlocking(false);
    oSock = oSockChan.socket();
    oSock.setKeepAlive(true);
    oSockChan.register(oSel,SelectionKey.OP_READ,new MyPacket(oSock.getInetAddress(),oSock.getPort()));
    break;
    case SelectionKey.OP_READ :
    oSelKey.interestOps(0);
    ((MyPacket) oSelKey.attachment()).inRequest(); *// preparing request*
    this.getReader().add(oSelKey); *// sending key to reading thread*
    break;
    case SelectionKey.OP_WRITE :
    oSelKey.interestOps(0);
    ((MyRequest) oSelKey.attachment()).inResponse(); *// preparing response*
    this.getWriter().add(oSelKey); *// sending key to writing thread*
    break;
    case SelectionKey.OP_CONNECT :
    default :
    *// nothing to do*
    catch ( IOException oExcept )
    *// do some actions*
    </pre>
    Timeouts are easily controlled by reading and writing threads (see OP_READ and OP_WRITE ).
    But when a client just connects without consequent data send, the state of this connection remains as OP_ACCEPT. The connection remains open for arbitrarily large time and I cannot control it!
    Please help with idea how can I terminate such connections!

    How can I process the keys that weren't selected at the bottom of the loop? Should I use the method keys() ?Yes. Form a new set from keys() and removeAll(selectedKeys()). Do that before you process selectedKeys().
    And the second moment: as I understood a single key may contain several operations simultaneously? Thus I should use several if's (but not if/else 'cause it's the equivalent of switch ... case ).If there is anything unclear about 'your switch statement is invalid. You need an if/else chain' I fail to see what it is. Try reading it again. And if several ifs were really the equivalent of "switch ... case", there wouldn't be a problem in the first place. They're not, and there is.

  • Release Invoice Price Block and Quantity Block

    Hi,
    How can I release the Invoice Price and Quantity block at the same time? I need to create a Step in a work flow to release all blocks of a two-way match block invoice.
    I've already tried to have a BDC for transaction MRBR but it is not working.
    Can anyone help?

    Hi Simi,
    This type of behaviour is documented in SAP note 394370:
    "A document generated with MIRO was blocked for payment.You cancel the
    payment block from the vendor line item in the FI follow-up
    document.Transaction MRBR then displays the invoice document
    nevertheless. Why?
    The invoice document itself cannot be changed by changes to the
    follow-up documents; this is not programmed.Transaction MRBR therefore
    continues to display the document as blocked. If this document is
    released from an MM point of view, the FI follow-up document remains
    released.Thus the damage caused is restricted to unnecessary work by the
    user.
    SAP recommends that you only use the release transactions for releasing
    invoices."
    MRBR generates its list of blocked invoices from table RBKP_BLOCKED and is the
    only transaction which deletes entries from this table thats why when your report
    calls FB02 to remove the payent block MRBR will still show the invoice as blocked.
    You could code in a pop up message in your report that prevents the user from
    deleting the payment block and to advise using MRBR instead to delete the block.
    Hope this helps,
    Adam.

Maybe you are looking for

  • Convert JAVA Web Dynpro to ABAP Web Dynpro application

    Hi, I was hoping someone could tell me if there is a way to port a JAVA Web Dynpro application to ABAP Web Dynpro. We have some JAVA WD apps that would now make more sense to have running on our ABAP system so we would like to convert them to ABAP WD

  • Customer master with holding tax data

    Hi, I am working on customer master transaction 'XD01'. I want add new fields to the existing subscreen 'with holding tax' and new fields in the new subscreen. There is  no enhancement is available for this, but there a BADI 'CUSTOMER_ADD_DATA_CS'. B

  • Wanted: Popup which allows the user to enter one string

    Hello, as the topic states, I am searching for a (modal) popup which lets the user enter one string in a text field and returns this string. I am currently using the function module 'POPUP_TO_GET_ONE_VALUE' for this purpose which works quite good - B

  • IPhoto 6.01 Still crashing

    No matter what I've tried, every time I edit a photo and click done the application crashes. Doesn't matter what photo. Doesn't matter what I do to it. Any ideas? It's driving me crazy. FYI I've run disk util from the install disk, I've run fsck in s

  • An unknowm error occurred (8364)

    Hello all, I'm getting "An unknown error occurred (8364)" when downloading certain songs from iCloud bought in the iTunes Store. I'm NOT using iTunes Match, as that seems to be the only place I've found a reference to this error message. Anyone know