Different thread behavior depending on condition - help!

Hi,
I have a multithreaded app in which, if certain certain predicate is met, then the current thread will execute some code before and after every invocation to a list:
foo() {
   //some code...
   if (predicate)
     do_stuff_before
     list.X
     do_stuff_after
  else
     list.X
  //some code...
}However, the evaluation of predicate() is very expensive. Therefore, I was wondering whether there is some way of dynamically changing foo such that
a) if the predicate has been set to false for the current thread, it executes
foo() {
//some code...
list.X
// some code...
}b) if the predicate has been set to true for the current thread, it executes
foo() {
//some code...
do_stuff_before
list.X
do_stuff_after
// some code...
}i.e., having two versions of the same code. Some threads execute version (a), while others execute version (b). Is this possible? How? Thanks!
Edited by: Leirado on Sep 11, 2009 9:15 AM
Edited by: Leirado on Sep 11, 2009 9:17 AM

You haven't made it clear, but I'm assuming that the value of the predicate is determined by various complex, expensive to evaluate conditions occurring independently of the worker threads. That is, the value of the predicate can change at any point before, during, or after execution of your before/list.X/after code.
Given that, I'd suggest on thread that simply loops to evaluate the predicate, and set s boolean flag as soon as it knows the truth or falsehood thereof. The worker threads read that flag for your if/else.
Make sure to either make the flag volatile, or synchronize all access to it.
TP: True predicate. This is whatever conditions external to the worker
and predicate eval threads are occurring that determine the truth of the
predicate.
PET: Predicate eval thread. Simply loops repeatedly to evaluate
the predicate, and at the end of each evaluation, sets a boolean flag
representing the latest value.
WT: Worker threads. They check the flag set by PET for the if/else
described in your first post.
TIME----------------------------------------------------------->
   init to              becomes true                           
TP-false--------------------+----------------------------------
                            |                                  
                           here                                
                                            now finds it true
     pred found  expensive code looping      |        
PET--initially---and taking much time to-----+-----------------
     false       evaluate full predicate...  |
                                           and sets flag
     flag==false     flag==false              flag==true
WT1--exec else--------exec else-----------------exec if-------------
                                 flag==false              flag==true
WT2-------------------------------exec else----------------exec if--

Similar Messages

  • GSS4492 provide different IP address depending on conditions

    Hi,
    I am new to GSSs to bear with me.
    We have 2 x GSS4492 configured as active/standby pair.  One exists in datacentre X whilst other exists in datacentre Y.
    We have a new requirement where by a 3rd part company will have a new WAN link connecting to our datacentre X and another to our datacentre Y. The 3rd party company will forward DNS lookups to the GSSs in both datacentres for a specific service - called application A. The GSSs sit behind a firewall in each datacentre. The GSSs will respond to a DNS query from 3rd party company with a NAT address on the firewall (designated as primary for the application) e.g. 10.10.10.10. 3rd party company then connects to the nat address etc. If the application A is not available in primary data centre then the GSSs will return an IP address for service in the other datacentre (nat address) 10.10.20.10. This is standard stuff - as far as I'm aware. 
    But, what they want is to use the same FQDN e.g. 'testing.test.co.uk' but require the GSSs to respond with a different IP address depending on a condition.
    - If application A is up in datacentre X and WAN link to data centre X is up (from 3rd party company) then GSS will respond to FQDN 'testing.test.co.uk' with 10.10.10.11 (local NAT address for service on this local primary datacentre)
    - If application A is up in datacentre X and WAN link to data centre X is down (from 3rd party company) then GSS will respond to FQDN 'testing.test.co.uk'  with 10.10.20.12 (other datacentre NAT address but this will be NAT'd to real address for application A in datacentre X)
    - If application A is down in datacentre X and WAN link to data centre X is up (from 3rd party company) then GSS will respond to FQDN 'testing.test.co.uk' with 10.10.10.12 (i.e. local datacentre NAT address but this is nat'd to real address of backup service in other datacentre i.e. application A in datacentre Y)
    - If application A is down in datacentre X and WAN link to data centre X is down (from 3rd party company) then GSS will respond to FQDN 'testing.test.co.uk' with 10.10.20.11 (backup datacentre Y)
    Can the GSS do this?  If so please indicate how it can be done (by the way the GSSs poll VIPs on ACEs in each datacentre).
    regards
    Mark

    yes. but then i have to go in and set my ip address manually everytime. because the the dhcp on both(work and home routers) just assigns whatever. i want to have a certain IP address depending on where i am, without having to actually tell the computer i'm at work now, or i'm home. because as soon as i walk into my office, i'm connected to the work wireless, so it should know, this address is 10.0.1.10, so the IP address should be 10.0.1.38. when i go home, it automatically connects to my home wireless, so it should look at the address and say, the IP should be this. just seeing if anyone figured how to do that?

  • How to display different Splash Screen depending on the Locale?

    Hi,
    I have a splash screen which is working fine.
    I want to display different spalsh screen depending on the locale the user has.
    Is this possible.
    I can display different Title,Description and the text of the short-cut icon on desktop and startup Menu based on the locale by mentioning it in the JNLP and altering my browser settings. I am not able to use the icon and splash screen corresponding to the specified locale. How to do this?
    EX:
    <information>
    <title> In english</title>
    <description> In english</description>
    <shortcut online="true">
    <!-- create desktop shortcut -->
    <desktop/>
    <menu submenu="My Project in English language"/>
    </shortcut>
    *<icon kind="shortcut" href="images/icon_english.gif"/>
    <icon kind="splash" href="images/splash_english.jpg"/>*
    <!-- locale="nl-NL" specifies dutch -->
    </information>
    <information locale="nl-NL">
    <title> In Dutch</title>
    <description>In Dutch</description>
    <shortcut online="true">
    <!-- create desktop shortcut -->
    <desktop/>
    <menu submenu="My Project in Dutch language"/>
    </shortcut>
    *<icon kind="shortcut" href="images/icon_dutch.gif"/>
    <icon kind="splash" href="images/splash_dutch.jpg"/>*
    </information>
    *Now here i am not getting the splash_dutch screen for the locale "nl-NL"(Dutch) and i am getting splash_english screen.
    Can we acheive this?*

    Hi anjali...
    I have problem with splash screen..
    here is my jnlp file
    <?xml version="1.0" encoding="UTF-8"?>
    <jnlp spec="1.0+" codebase="http://localhost:8080/MyProject">
         <information>
              <title>MyProject1.0</title>
              <vendor>none</vendor>
              <description>Application Launcher For MyProject1.0</description>
              <description kind="short"></description>
              <offline-allowed />
              <icon kind="splash" href="images/Splash_MyProject.jpg" width="560" height="300"/>
         </information>
         <resources>
              <jar href="SwingApplication/mysql-connector-java-5.0.6-bin.jar" />
              <jar href="SwingApplication/MyProject1.0.jar" main="true"/>
              <jar href="SwingApplication/liquidlnf.jar" />
              <j2se version="1.6+" java-vm-args="-Xms32M -Xmx256M " />
         </resources>
         <security>
              <all-permissions/>
         </security>
         <application-desc main-class="com.mobius.ui.MainWindow">
              <argument>production%0%3#com.mysql.jdbc.Driver#MyProject4%jdbc:mysql://10.100.1.89:3306/MyProject4%MyProject%info123#MyProject2%jdbc:mysql://10.100.1.89:3306/MyProject2%MyProject%info123</argument>
         </application-desc>
    </jnlp>my post is in
    http://forum.java.sun.com/thread.jspa?threadID=5298381
    http://forum.java.sun.com/thread.jspa?threadID=5298466
    I am in big problem Help me...
    Edited by: arunnprakash on May 22, 2008 1:28 PM
    Edited by: arunnprakash on May 22, 2008 1:28 PM

  • Thread problem depending on the OS

    Hello !
    I'm developing a Java CORBA server application with JDK1.2.2.007, it contains a lot of threads and synchronized blocks - multithreading use. I have the following weird behavior depending on the OS:
    The startup of my server is for instance the ORB mainloop (let's say like a graphical event loop).
    - on WIN32 the CPU gets stuck to 100% after startup (without any activity)
    - on Solaris it is not reproducible
    - on HP neither
    After performing a client request on my NE:
    - on WIN32 (2K) the CPU keep stuck to 100% (I'm not astonished anyway)
    - in Solaris (spark) the CPU gets stuck to 100% after this first client request (but no activity after the request is completed)
    - on HP the problem is unreproducible (at any time).
    We're developing on SUN and we've came to the point that we have to use 2 workstations: one to run the server and one to run the client coz the CPU problem. By chance my target is on HP ;-)
    At one given time, a lot of threads do exist (for instance the Orbacus threadpool). I've tried to analyze with JVM options -Xrunhprof:heap=sites,cpu=samples,depth=10,monitor=y,thread=y,doe=y with not real success.
    I've heard about Amdahl's law but I'd like to know how I can analyze that the problem comes from the object creation, garbage collection, and/or synchronied methods/blocks. Does anybody know much about how to track this law in real code ?
    -> if so, how to detect these blocks ?
    -> if so, can I instrument the JVM to solve the problem ?
    Thanks for help.
    Sebastien.

    There certainly isn't any evidence that threads on Sun or Windows normally pegs the cpu. At least not without activity.
    So that certainly suggests that your code does impact it in some way.
    I am guessing that you are also not using the same vendor for the JVM on all boxes? Sun doesn't make one for HP.
    How many threads are you creating?
    Threads wait on objects. Presumably when you start it up you are waiting for some signal to start processing? And the only way to block would be to wait on a system resource like a socket. So what type of resource are you blocking on at start up?

  • Is there a way to run two different threads indefinitely

    I have two different threads and they both are doing different tasks.... I want them to be running indefinitely....
    i want the threads to run indefinetly passing the control between one another( anyway, passing the control is unpredicatable)
    I dont want the tasks to be run in a infinite loop but the threads itself, which are doing their respective tasks.....

    vinney_143 wrote:
    anyway, with respect to what i understood, this is what i tried.............. i thought of calling the start() methods within a loop but it should be throwing illegalThreadStateException. so, i came to this forum to seek some help on this.
    If i am gonna put the loop inside the threads, i dont think that serves my purposes of calling two threads indefinitely and not doing a task in each thread indefinitely........Threads have states: NEW, RUNNABLE, BLOCKED, WAITING, TERMINATED. When you create a thread (as an instance of thread) it is in NEW state. When you call start() on the thread instance it goes into RUNNABLE state. Process scheduler chooses a thread in runnable pool and runs it on the processor. When a thread goes to RUNNABLE etc states it can not go to NEW state (thats illegal). From a RUNNABLE state thread can only go to BLOCKED, WAITING or TERMINATED states. You can't call start() on the thread more than once. Once a thread is terminated (TERMINATED state) it can't go to NEW state either. Once start() is called the thread is started and you write logic that determines when the thread is terminated. Thats the reason why you got an IllegalThreadStateException.
    while(true) {
        thread.start(); // throws IllegalThreadStateException
    }Heres one way to keep thread running till a certain condition is met.
    class MyThread extends Thread {
        public void run() {
            while(true) {
                boolean condition = //
                if(condition) {
                    return; // terminates thread because run() returns
    }Hope this helps.

  • IPhone sending texts to two different threads

    I have an iPhone 4S running iOS 6.1.3 and I'm on the Sprint network.
    To preface, way earlier this summer I sent out a message to several people, all with iPhones with iMessage enabled. Turned out that the contact info I had for one of the contacts on my phone, let's call him Friend 1, was wrong (I somehow had an 8-digit phone number for him, I guess I had just entered the information incorrectly and never texted him before). The texts were obviously going to everyone except Friend 1. So I corrected his contact info with his correct number, made a new group thread, and all was better.
    Then two days ago, another one of my friends (Friend 2) in the same group thread turned off his iMessage because he's got a different bug on his phone that makes it freeze up every time he sends an iMessage. Anyway, as I expected, every message I send in the group thread is now green, being sent as an SMS. But everyone else in the thread is still able to send iMessages to it, which Friend 2 receives, despite having turned off iMessage on his phone.
    However, whenever I try to send a message, I'm almost always only able to send an SMS. One of my other friends (Friend 3) informs me that all my SMSes sent since Friend 2 turned off his iMessage have been going to a different thread, the one from months ago with Friend 1's number entered incorrectly. I can see every message that everyone else sends in the thread, including those of Friend 1, whose contact info is still correct. Occasionally when I open the thread I'll be able to send an iMessage, which everyone receives, but most of the time I'm only able to send SMSes, which go to the broken thread that everyone except Friend 1 can see. On my phone, though, it looks like I'm sending and receiving every message in the same thread with all the info correct, and every message that any of my friends send in either thread comes into the one thread on my phone with Friend 1's number entered correctly.
    Whenever I text Friend 1 individually or in any thread that doesn't have Friend 2 (who turned off iMessage) in it, everything works perfectly. I have no problem in any other iMessage conversation. But the thread with all of us in it together presents these problems where any time I'm not able to send iMessages, the SMSes appear to me to be sent in the same thread, but for everyone else (except Friend 1 who can't see them at all) they go into the old broken thread.
    To clarify, whether or not I'm able to send iMessages seems to turn on and off arbitrarily between texts, that is to say, it doesn't seem to be corrolated to whether or not anyone in the thread is or isn't connected to the network.  I'll send a few SMSes in the thread, which go to the broken one, and then my phone will be able to send one iMessage, and I can wait as long as I want to send it- the capability doesn't go away with time, but as soon as I send the one iMessage I can't send any more. That iMessage goes to the good thread, and then it'll turn back to SMS for either a random period of time or a random quota of SMSes sent, I can't tell.
    Basically I can't understand how this could be happening. I don't get how I could be sending these texts to a number that I don't have in my phone. I don't get why iMessage seems to turn on and off arbitrarily for me alone in this one group thread. I also don't understand how someone (Friend 2) with iMessage turned off can be receiving iMessages in a group thread but can't send them himself or receive them when someone texts him alone, but that's not a problem, just a related curiosity.
    I know this is a huge explanation, but I just wanted to be as thorough as possible. If any clarification is needed just let me know. Thank you guys for any help you can provide.

    No problem. However, like I said earlier, music is a sync, no problem since that content is on a computer. Contacts and calendar is a sync, no problem since that content is on a computer as well. Just make sure there is a file backup of those components. The next thing is to save pictures and other data. I suggest you have a sync of both computers to the phone, and then do a backup on your personal computer. I would also import the pictures to the personal computer as a bakup, however you can keep them in the Camera Roll if you want after you have imported them. This ensures you have data backed up. Restore the new phone to the backup on your personal computer. Make sure it is set to only sync music.You should get your data, and then it can resync the music. Make sure the work computer is only setup to sync manually and to sync just contact and calendar data and nothing else. Connect the phone to that computer and sync. You should get your contacts and calendar. Now you might get a warning box saying the iPhone is synced to another library, but don't worry since the work computer is not setup to sync music. Now remember, this is my 2cents worth based on what information you provided. You cand decide if you want to do this or not and you make your choices on your own.

  • How can I setup an .indd with two columns with different threads so that I can export to epub?

    Hi all. Sorry, english is not my native language. I´ve made an .indd: each page has two columns with different threads (is a bilingual text). When I export this .indd to .epub only appears one column from a thread following the next thread. What can i do to fix this? My indesign is CS6
    Thank you

    There are fixed format EPUB files as can be used for children's books, etc. where there are a lot of illustrations. However, those are very work-intensive to produce. I've never worked on one.
    Anne-Marie Concepcion did a Lynda.com video on producing one.
    Rorohiko produces a product called ePubCrawler which can help in produced fixed format EPUB files:
    Fixed Layout EPUB Assistant In InDesign: ePubCrawler | Rorohiko ...

  • Monthly purchase value,depending on condition type used.

    Can we search for PO,depending on condition type used in the PO.eg. we are using a condition ZENT for entry tax and
    the requirement is to search the po containing that ZENT condition.In dynamic selection mode there is condition group in
    purchase order detail,but it is not selecting the required PO.please guide.

    Hi,
    This requirement is not possible in std SAP Report.
    You need to develop a Z report with the help of ABAPers.
    Give proper logic for them for creating this req.
    Regards,
    Rahul

  • How to remove fire action to image field depending on condition

    Hi,
    I have one field as Image and having fireaction event in table and all remaining fields are Mesagestyled text
    Requirement is need to remove fire action for action some rows depending on condition.
    Pls help, how to do this?..
    Thanks in advance,
    Hanimi..

    Hanimi,
    You need to make use of switcher Region, for achieving your requirement. Refer Developer Guide for more details on Switcher Region.
    Regards,
    Gyan

  • Differance betwwen alternative calculation type & condition base value.

    dear expert
    wats the differance betwwen alternative calculation type & condition base value in pricing.
    vicky

    Hi,
    AltCty - Condition formula for alternative calculation type:
    It is an alternative formula for the condition type that can be used instead of standard formulas.
    For example, let us take the Profit Margin which can be both + / - , so here this routine will help us in generating the value which can be either + or -. Profit margin is not a condition type so it cannot be classified as +ve or -ve in the V/06.Ex.: 950 0 Profit Margin 11. So we assign 11 - Profit Margin.
    AltCBV - Alternative formula for condition base value:
    Formula for determining the condition basis as an alternative to the standard.
    It is used as a basis to calculate value of the condition type instead of using it from the "FROM" column.
    Ex.: Freight - KF00. Freight is calculated based on weight, volume etc. and not on the base price. In pricing there is no entry of weight from which the value can be referred like we do for discounts using base price. We have to get the value from the Material master. In this column we can mention the value as 12 - Gross Weight or 13 - Net Weight.
    During pricing, the system will consider the value that is mentioned in this column and determine the freight based on this value.
    Suppose we have Net weight: 100 kgs and Gross Weight: 150 kgs. And if we mention 13 in this column then the Freight condition KF00 will be calculated using the weight as 100 kgs.
    And both of them are routines written by APABers in VOFM.
    Reg,
    JJ

  • How to set colors in cells depending the conditions  in alvtree

    Hi All,
    Could you please provide me idea or sample program how to set colors in cells depending the conditions  in alvtree.
    Thanks,
    Suresh

    When running vim in a terminal, it will use whatever colour scheme is defined by the terminal.  You should have a look at this thread:
    http://bbs.archlinux.org/viewtopic.php?id=51818
    Also, check the wiki article on Xdefaults.

  • Run sql query on a different thread

    Hello,
    I have a swing app that queries an MS SQL database and it works fine and everything happens in the same thread. However for improved performance and to avoid freeze ups, I want the SQL queries themselves to execute on a different thread as a different class, other than the swing app class. The query results (Result Set) I want them back to my swing app so I can present them on a JTable.
    Here is an example of what I am trying to accomplish:
    - Press button in my swing app.
    - Call class that implements Runnable
    - In the Run method of the new class do the following (this code will execute in a new thread):
    url = "jdbc:sqlserver://ServerName:1433;databaseName=Database;user=UserName;password=password";
    try{
         Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
         Connection con = DriverManager.getConnection(url);
         Statement stmt;
         ResultSet rs;
         stmt = con.createStatement();
         String queryString = "select * from databaseName";
         rs = stmt.executeQuery(queryString);
          con.close();
    catch(Exception em){
          em.printStackTrace();
         JOptionPane.showMessageDialog(null,em.toString());
    }- Get the ResultSet rs back from the class
    - Work with the results back in my swing app and present them in the JTable
    while(rs.next()){
                //do some stuff
         }Any help or hints are greatly appreciated.
    Thanks,
    Chris

    Two suggestions:
    -- Take a look at SwingWorker for taking care of the threading issues
    -- Keep all database handling code together. Collect the records into a Collection -- most likely ArrayList -- and return that. This way you can close the Connection and RecordSet within the same method that opens them.
    Just my 0.02.
    db

  • Can I assign different Spry widgets depending on device?

    Using Fluid Grid Layout, is there a way I can display the same html in a Spry Accordian for phones only and a Spry Tabbed Panel for tablets and desktops?

    The mechanism that makes the Spry Accordion slide up and down when a user click each panel, in the image below, is different than the mechanism that makes a Spry Tabbed Panel switch from panel to panel when a user clicks each tab (image below this one).  This mechanism is called "Widget Behavior: JavaScript code that controls how the widget responds to user-initiated events."  It is my understanding that CSS only controls the look and style of something and not the way it behaves.  Again, I appreciate your attention to this matter but I am looking for a way to display the same html in a Spry Accordion for phones only and a Spry Tabbed Panel for tablet and desktops. This requires that I use different javascript code depending on device. I understand how to change the CSS depending on device.

  • Modifying an NSMutableDictionary from a different thread that created it?

    I've been getting a execbadaccess error when I try to do this (setObject: count:, etc).
    Any reason why NSMutableDictionary doesn't like it when you try to modify it from a different thread?
    Thanks

    Can anyone tell me why this code breaks at runtime? It spits out this error:
    "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSCFSet setObject:forKey:]: unrecognized selector sent to instance ..."
    - (void)applicationDidFinishLaunching:(UIApplication *)application {
    md = [NSMutableDictionary dictionaryWithCapacity:10];
    [NSThread detachNewThreadSelector:@selector(update) toTarget:self withObject:nil];
    [window makeKeyAndVisible];
    -(void) update {
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    NSString *key = @"Key";
    NSString *value = @"Value";
    [md setObject:value forKey:key];
    [pool release];
    I don't understand it. I stepped through it with the debugger and 'key', 'value', and 'md' are all non-nil instances.
    Thanks for any help
    {quote}
    You're trampling another execution context's address space. It might crash, it might not. Lock before you write. {quote}
    I would understand that if I had two different threads both trying to add objects to this, but I create the dictionary in the main thread, then spawn a thread an access it. It shouldn't need locks since there's only one thread writing to the dictionary after it was created.

  • Running the TSQCallback function in a different thread?

    Hi,
    I am looking at the example code directPtrAccess.c where the TSQcallback function is set to be executed in the same thread that generates the data. However, in application, I would like to run the call back function in a separate thread.
    I would greatly appreciate if some one can clarify whether this is possible and if yes how it should be done?
    Thanks!
    Sripad

    In that example the TSQ callback is not executed in the generation thread: it is executed in the main thread instead.
    The generation thread is unknown (the thread ID is not saved in any variable) but is it different from the main thread, which is the one that handles the user interface.
    As you can see, the TSQ callbacl is installed receiving CmtGetCurrentThreadID() in Callback Thread ID; that is to say, it receives the ID of the main thread and executes there.This is a very common situation, where generation / acquisition of data and other tasks are executed in a separate thread and presentation of data and UI handling are executed in the main thread.
    If you had previously created a different thread and saved its ID, you could pass it in this parameter and obtain the callback to run in that thread.
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?

Maybe you are looking for

  • How can I transfer my music from an Ipod to my new MAC? My old computer broke.

    My old computer broke.  I got a new MAC Book PRO.  I have all may music in an Ipod classic.  Can I recover my music to my new MAc?

  • Trying to understand compareTo()

    Hello again world. Please excuse my thickness. I have two issues with the compareTo() method which I think are unrelated. I have an array of "Employee" objects. The array is called "emp" which I sort in main]/b] with the call [b]Arrays.sort(emp) and

  • AdfFacesContext was already released or had never been attached JSP v. JSPX

    This error is occuring on JSPX pages but not on JSP pages and only when I deploy the application to Oracle 10gAS 10.1.2. The problem does not normally present itself in JDeveloper (10.1.3). I had tried moving all my pages to the JSP form but found th

  • Purchase Requisation

    Dear All, I want to configure Purchase Requisation for service procurement from third party in CRM SRMV and SRVP item category. Can any body help me to configure or any document. Thanks in advance Neeraj

  • Patches in screen painter

    Hi Experts... while designing screens in screen painter i am switching to the alpha screen editor... i have search for the problem but the the graphical layout editor is not getting started... any idea..