Multi-threading problem

Hello everybody,
I am having a problem using OCCI and threads.
First I have Oracle RAC, I launched 5 threads from my application to do some query each thread has its own parameters to the same query but all are accessing the same table which is created with nolog option.
The problem is the application always crashes whenever the threads are all at the same point of getting result set and specifcally at next() .
I am suspecting that result set returned is null or paralle execution of the query has problem.
P.S.: I have a connection pool which I use to get connection for each thread separately. The environment object is created with Object I tried to create the environment with Multithreaded_mutexed | object but it crashes while executing the app.
Can anybody help ?

Are you creating the environment as shown below?
Environment *env = Environment::createEnvironment(Environment::Mode((Environment::OBJECT|Environment::THREADED_MUTEXED)));                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • Multi-Instrument + Multi-Thread problem found

    Right.....I have done a lot of research on why logic was not multi-threading correctly and have narrowed it down to one problem...using Kontakt as a multi instrument.
    My Mac is a 2 x 2.26 GHz Quad-Core Intel Xeon. This means that it is capable of distributing work loads over the multiple cores of the CPU to prevent core audio overloads from happening.
    If I run any plug ins in stereo or mono mode, the CPU acts as it should; I will load up a program, add processing and when the load is becoming a strain for the CPU, I use a bus send and work on that, then the workload is redistributed across more of the cores by logic, allowing me to continue working.
    However, I need to use Kontakt as a multi instrument. I usually have 3 instances of Kontakt open and on each one of these, I usually have a minimum of 10 outputs being sent to the aux channels of logic. Therefore using Kontakt as a stereo instrument is not an option, as I would have to open around 30 instances!
    Here is the problem; say for example, in Kontakt I send a kick drum out of Kontakt into AUX 3 + 4. The AUX channel in logic will being to show output. I can now EQ this single kick drum seperate from any other sound in logic.
    If I began to add processor heavy plug ins to this AUX output, rather than share the workload across the cores as it should and does with stereo instruments, logic now only uses a single core and it will core audio overload very quickly.
    As I said, this only happens when I set up Kontakt as a multi instrument. The main problem is when I begin to have many different outputs from my 3 instances of Kontakt, as by this stage, many different sounds will have processing. All 3 multi instruments and their processing are then controlled by the single processor and the other 7 are almost inactive! It therefore becomes impossible to use Kontakt and I have to switch to stereo instances. This happens for all multi-instruments not just Kontakt.
    I have just purchased Kontakt 4, I am upgrading to OSX 10.6 (Snow Leopard) and am updating Logic to v9.1. (From v9.0) Will this help at all? Is there an answer to this problem or will I just have to open 30 stereo and mono instances of Kontakt to continue working!
    I have included a link to a ZIP file with two photos of the problem. In the photo named MASSIVE. I have one instance of massive running as a stereo instrument. It is sent to a BUS where I applied the WAVES L316 Limiter. I did this multiple times and if you can see on the system performance (Top right) Logic is sharing the workload over the processors as it should.
    In the second picture named KONTAKT MULTI - I have done the same thing, but I have opened Kontakt as a multi instrument, sent a kick drum to AUX 2 and then forwarded this to a send where I applied the same WAVES L316. You can see on the system performance meter (Top Right) that Logic now does not re-distribute the workload, it is using one core and anymore plug ins applied to the AUX or bus channels relating to Kontakt will now make it core audio over load, even though now I am using far less processing.
    PHOTOS: http://www.sendspace.com/file/og8a94

    Ditto
    Using Pro 8 Studio, I had this problem after installing Snow Leopard.
    Invested £159 in Pro 9 update, same problem.
    This has stopped most of my work since my external WK4 sounds are superior to the included software sounds.
    As suggested, will now report since since it obviously seems to be a general problem.

  • Fix Multi thread problem

    Hi everyone
    I have a main program that tries to run two threads. here is the part of the main
    R_Thread rThread1 = new R_Thread(9);
    Thread t1 = new Thread(rThread1, "first");
    t1.start();
    R_Thread rThread2 = new R_Thread(8);
    Thread t2 = new Thread(rThread2, "second");
    t2.start();and here is my runnable:
    public class R_Thread implements Runnable {
         private int ID = -1;
         public R_Thread(int location){
             ID = location;
         public void run() {
              try {
                   while (true) {
                       dostuff();
                           Thread.sleep(5000);
              catch(InterruptedException e) {
                       System.out.println(e.toString());
        public void dostuff() {
    }as you can see i'm trying to run two threads but with different ID's. my program is supposed to read the data, process it and store it in DB. this works well but sometimes it misses to process the data. like it skips some data and continues with the other. my best guess is two threads are interfering with each other.
    i apologize for being vague but i don't know how else can i explain. Please feel free to ask any question, hopefully i can explain better. can anyone recommend me something to fix this?? thanks

    hey guys thanks for the input. i am trying to implement something different now.
         public class R_Thread implements Runnable {
              private int ID = -1;
              public R_Thread(int location){
                   ID = location;
              public void run() {
                   try {
                        while (true) {
                             if(Thread.currentThread().getName().equals("first")){
                                  dostuff();
                                  Thread.currentThread().wait();
                                  //notify to resume thread "second"
                             else if (Thread.currentThread().getName().equals("second")){
                                  dostuff();
                                  Thread.currentThread().wait();
                                  //notify to resume thread "first"                              
                   catch(InterruptedException e) {
                        System.out.println(e.toString());
              public void dostuff() {
         }how can i do this?? also i got this IllegalMonitorStateException error, how can make currentthread owner of the monitor?
    Edited by: d_khakh on Jun 4, 2009 2:33 PM

  • Java Multi Thread problem.

    Hi guys . . . i need so much help. i am trying to implement matrix multiplication using threads.
    For some reason when iam multiplying the matrices i have the threads waiting too long.. they wait wait wait.. then do the job and then wait wait wait.
    Here is the code for my thread pool class
    package concurentNaive;
    import java.util.*;
    public class ThreadPool {
         protected Thread threads[] = null;     
         protected EndPool endPool = new EndPool();
         Collection jobs = new ArrayList(5);
         public PriorityQueue<MatrixJob> pq = new PriorityQueue<MatrixJob>();
         public ThreadPool(int size,PriorityQueue qu){
              this.pq = qu;
              threads = new worker[size];
              for (int i=0;i<threads.length;i++){
                   threads[i] = new worker(this);
                   threads.start();
         public synchronized void assign(Runnable r){
              endPool.workerBegin();
              jobs.add(r);
              System.out.println(Thread.currentThread());
              notify();
         * Get a new work
         * @return
         public synchronized Runnable getAssignement(){
              try {
                   while ( !jobs.iterator().hasNext() )
                        wait(1);
                        System.out.print(Thread.currentThread());
                   Runnable r = (Runnable)jobs.iterator().next();
                   jobs.remove(r);
                   return r;
                   } catch (Exception e) {
                        endPool.workerEnd();
                   return null;
         public void complete(){
              endPool.waitBegin();
              endPool.waitDone();
         protected void finalize(){
              endPool.reset();
              for (int i=0;i<threads.length;i++){
                   threads[i].interrupt();
                   endPool.workerBegin();
                   threads[i].destroy();
         * Class for the pool component threads.The thread scans and executes tasks.
         * @author Krack
         class worker extends Thread{
              public boolean busy;
              public ThreadPool owner;
              worker(ThreadPool o){
                   this.owner = o;
              public void run(){
                   Runnable target = null;
                   do {
                        target = owner.getAssignement();
                        if (target!=null) {
                        target.run();
                        owner.endPool.workerEnd();
                        } while (target!=null);
    and here is my thread :
    ublic class TheWorker implements Runnable{
              private int[] answer;
              private MatrixJob myJob;
              private long time1;
              public TheWorker(MatrixJob job){
               this.myJob = job;
               time1 = System.currentTimeMillis();
               public void run()
                    //MatrixJob theJob = this.myJob;
                    answer = new int[myJob.row.length];
                    for (int i=0;i<myJob.row.length;++i){
                         for (int j=0;j<myJob.cols.length;++j){
                              answer=0;
                             for (int k=0;k<myJob.cols[j].length;k++){
                                  answer[i] += myJob.row[i]*myJob.cols[j][k];
                        for(int i=0;i<answer.length;i++){
                             System.out.print(answer[i]+" ");
                        }     System.out.println();
              public int[] getAnswer() {
                   return answer;
    Any help is much appreciated. Thank you much.

    How do you know that they are waiting?

  • The problem about multi-thread in java application

    i have problem with the multi-thread in java application, i don't know how to stop and restart a thread safely, because the function thread.stop(),thread.suspend() are both deprecated.
    now what i can only do is making the thread check a flag(true or false) to determine whether to start or to stop, but i think this thread will always be in the memory and maybe it will lower the performance of the system, as the program i am developping is working under realtime enviorement.
    please help me about it. thanks !

    hi,
    you can stop a thread by exiting it's run()-method which in terms can be done by checking the interrupted-flag:
    public void run(){
    while(interrupted()){ //if the thread consists of a loop
    or
    public void run(){
    if(interrupted())return;
    if(interrupted())return;
    or by the use of the return-statement anywhere withing the run-method. Afterwards, that is when the thread is no longer needed, you clear all the references to the specific thread object by setting them to null:
    Thread t;
    ... //working
    t.interrupt(); //interrupting
    while(t.isAlive()){
    Thread.yield(); //wait till thread t has stopped
    t=null;
    best regards, Michael

  • The problem of profiling a multi-thread flash game  using adobe scout cc

    I have a multi-thread flash game code, it can run perfectly. The main swf creates another swf which will connect to a remote server. I can get profiling information of the main swf  using adobe scout cc, but the problem is that I can't get profiling information of another swf ! The scout complains " can't start a session because the telemetry data isn't valid" for another swf. Although some times, the scout does not complain, the Summary Panel of scout provides information“We encountered an error while processing this session: Some of the data we present may not be correct". And the scout log file shows:
    Log file created: 2014/11/20 15:35:08
    11/20/2014 15:35:08.395 Scout starting up.
    11/20/2014 15:35:08.471 InitDNSService failed
    11/20/2014 15:36:47.055 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [100000,200000] is greated than its parent
    11/20/2014 15:36:47.057 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [200000,300000] is greated than its parent
    11/20/2014 15:36:47.058 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [300000,400000] is greated than its parent
    11/20/2014 15:36:47.058 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [400000,500000] is greated than its parent
    11/20/2014 15:36:47.061 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [500000,600000] is greated than its parent
    11/20/2014 15:36:47.062 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [600000,700000] is greated than its parent
    11/20/2014 15:36:47.063 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [700000,800000] is greated than its parent
    11/20/2014 15:36:47.063 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [800000,900000] is greated than its parent
    11/20/2014 15:36:47.064 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [900000,1000000] is greated than its parent
    11/20/2014 15:36:47.064 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [1000000,1100000] is greated than its parent
    11/20/2014 15:36:47.064 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [1100000,1200000] is greated than its parent
    11/20/2014 15:36:47.065 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [1200000,1300000] is greated than its parent
    11/20/2014 15:36:47.065 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [1300000,1400000] is greated than its parent
    11/20/2014 15:36:47.065 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [1400000,1500000] is greated than its parent
    11/20/2014 15:36:47.066 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [1500000,1600000] is greated than its parent
    11/20/2014 15:36:47.066 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [1600000,1700000] is greated than its parent
    11/20/2014 15:36:47.066 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [1700000,1800000] is greated than its parent
    11/20/2014 15:36:47.067 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [1800000,1900000] is greated than its parent
    11/20/2014 15:36:47.067 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [1900000,2000000] is greated than its parent
    11/20/2014 15:36:47.067 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [2000000,2100000] is greated than its parent
    11/20/2014 15:36:47.068 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [2100000,2200000] is greated than its parent
    11/20/2014 15:36:47.068 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [2200000,2300000] is greated than its parent
    11/20/2014 15:36:47.068 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [2300000,2400000] is greated than its parent
    11/20/2014 15:36:47.069 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [2400000,2500000] is greated than its parent
    11/20/2014 15:36:47.069 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [2500000,2600000] is greated than its parent
    11/20/2014 15:36:47.069 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [2600000,2700000] is greated than its parent
    11/20/2014 15:36:47.070 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [2700000,2800000] is greated than its parent
    11/20/2014 15:36:47.070 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [2800000,2900000] is greated than its parent
    11/20/2014 15:36:47.070 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [2900000,3000000] is greated than its parent
    11/20/2014 15:36:47.071 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [3000000,3100000] is greated than its parent
    11/20/2014 15:36:47.071 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [3100000,3200000] is greated than its parent
    11/20/2014 15:46:30.931 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [100000,200000] is greated than its parent
    11/20/2014 15:46:30.933 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [200000,300000] is greated than its parent
    11/20/2014 15:46:30.936 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [300000,400000] is greated than its parent
    11/20/2014 15:46:30.937 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [400000,500000] is greated than its parent
    11/20/2014 15:46:30.937 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [500000,600000] is greated than its parent
    11/20/2014 15:46:30.937 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [600000,700000] is greated than its parent
    11/20/2014 15:46:30.937 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [700000,800000] is greated than its parent
    11/20/2014 15:46:30.938 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [800000,900000] is greated than its parent
    11/20/2014 15:46:30.938 <2896> <telemetryCore.Query> <1> Incorrect data: Memory category 7 for frame stats query over time interval [900000,1000000] is greated than its parent
    I run flash code directly on flash_player_11_7_sa.exe. I think the problem may have something to do with ActionScript Sampler of scout, because I can get the correct profiling information  without ActionScript Sampler.
    But I don't know what the information in the log file means.

    We are using Microsoft SQL Server 2008 . but it's well with MySQL & JBoss

  • PROBLEM OF MULTI-THREAD?????

    Hi I'm writing a program like Multi-tap (the text entry before T9 introduced) on mobilephone.
    I'm having problem with some of the KEYs. They do not work properly.
    As indicated in the code
    HERE HERE [3] suppose to function as space button....However whenever the key is pressed before the 'time out' (I use sceduler to implement the time out) it will print half of the previous character instead of space. this key is not related to the scheduler. so i suspect it is something related to multi-thread programming.
    HERE HERE [1] function as the caps lock. it can even show the indicator properly.... so i need to settle this b4 i continue.
    HEREHERE [2] function as clear button. it doest work too
    Someone please help me....
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package textEntry;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.*;
    import java.util.*;
    * @author Ed's
    public class MyCanvas extends GameCanvas {
        public static final String[] keys =
        {".?!,@`-_:;()&\'\"~10�$��+x*/\\|[]=<>#","abc", "def", "ghi", "jkl",
        "mno", "pqrs", "tuv", "wxyz"};
        public static final String[] capitalKey =
        {".?!,@`-_:;()&\'\"~10�$��+x*/\\|[]=<>#","ABC", "DEF", "GHI", "JKL",
        "MNO", "PQRS", "TUV", "WXYZ"};
        StringBuffer width = new StringBuffer();
        Timer keyTimer;
        textEntryMain main;
        public static char ch;
        public boolean keypress=false;
        public boolean capital;
        public boolean diffrentKey;
        String currentIndicator="abc";
        int countPress=0;
        //int previndex=0;
        public int counter=-1;
        int index=-1;
        int print=0;
        int white_space=6;
        public StringBuffer sms;
        int baseline=10;
        int y_axis=12;
        int line=1;
        char last;
        boolean dontPrint=true; //dont print if timer printed or it is at begining
        Font font;
        Graphics g;
        public long time;
        int poundHit=0;
        String justPressed;
        String prevPressed=null;
        char prevChar;
        //Sms class
        Form smsfrm;
        TextField smsField ;
        //Char Selection speed
        public boolean first;
        int selection_speed=1500;
        //font color (blue)
        public int red=0,green=0,blue=255;
        //Background color (white)
        public int back_red=250,back_green=250,back_blue=250;
        Form menu;
        public MyCanvas(textEntryMain main){
            super(false);
            first=true;
            this.main=main;
            sms=new StringBuffer();
            g=getGraphics();
            font=Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_BOLD,Font.SIZE_LARGE);
            keyTimer = new Timer ();
            keyTimer.schedule (new task (this), selection_speed, selection_speed);
            drawIndicator(currentIndicator);
        public void drawIndicator(String indicator){
            Font f = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_ITALIC, Font.SIZE_SMALL);
            Graphics g = getGraphics();
            g.setFont(f);
            int x= getWidth()-20;
            g.setColor(back_red,back_green,back_blue);
            g.fillRect(x,2,15,10);
            g.setColor(20,20,20);
            g.drawString(indicator, x, 2, g.TOP|g.LEFT);
        public void callPaint(char ch){
            drawIndicator(currentIndicator);
            Graphics g= getGraphics();
            g.setColor(back_red,back_green,back_blue);
            if(first){
                g.fillRect(0,0,getWidth(),getHeight());
                reset();
                redrawAll();
                first=false;
            //baseline -1 so that i can cover the pointer
            g.fillRect(baseline-1,y_axis,font.charWidth(this.last)+3,font.getHeight());
            g.setColor(red,green,blue);
            g.setFont(font);
            g.drawChar(ch,baseline,line*24,g.LEFT|g.BASELINE);
            flushGraphics();
        public void showPointer(){
            Graphics g = getGraphics();
            g.setColor(0,0,0);
            g.drawLine(baseline,y_axis,baseline,2*line*12);
            flushGraphics();
        //pointer appear //pointer disappear-use white line so that it cover the pointer line
        public void hidePointer(){
            Graphics g = getGraphics();
            g.setColor(back_red,back_green,back_blue);
            g.drawLine(baseline,y_axis,baseline,2*line*12);
            flushGraphics();
        //draw the selected
        public void ConfirmPaint(char ch){
            Graphics g = getGraphics();
            sms.append(ch);
            g.setColor(red,green,blue);
            g.setFont(font);
            g.drawChar(ch,baseline,line*24,g.LEFT|g.BASELINE); //draw the selected
            baseline+=font.charWidth(ch); // so that the nect letter won't be drawn on the same position
            if(baseline>getWidth()-30){     //move to the next line
                width.append((char)baseline);
                baseline=10;y_axis+=24;
                line+=1;
            flushGraphics();
        public synchronized void deleteChar(){
            if(sms.charAt(sms.length()-1)==' '){
                baseline-=white_space;
                Graphics g= getGraphics();
                g.setColor(back_red,back_green,back_blue);
                g.fillRect(baseline,y_axis,font.charWidth(sms.charAt(sms.length()-1))+2,font.getHeight());
                sms.deleteCharAt(sms.length()-1);
            else{
                baseline-=font.charWidth(sms.charAt(sms.length()-1));
                Graphics g= getGraphics();
                g.setColor(back_red,back_green,back_blue);
                g.fillRect(baseline,y_axis,font.charWidth(sms.charAt(sms.length()-1))+2,font.getHeight());
                sms.deleteCharAt(sms.length()-1);
            flushGraphics();
        public void redraw(char ch ){
            Graphics g= getGraphics();
            g.setColor(red,green,blue);
            g.setFont(font);
            g.drawChar(ch,baseline,line*24,g.LEFT|g.BASELINE);
            baseline+=font.charWidth(ch);
            if(baseline>getWidth()-30){
                width.append((char)baseline);
                baseline=10;y_axis+=24;
                line+=1;
            flushGraphics();
        public void reset(){
            if(width.length() >0)
            width.delete(0,width.length()-1);
            line=1;
            baseline=10;y_axis=12;
        public void redrawAll(){
            Graphics g=getGraphics();
            g.setColor(back_red,back_green,back_blue);
            g.fillRect(0,0,getWidth(),getHeight());
            reset();
            for(int a=0;a<sms.length();a++)
            redraw(sms.charAt(a));
        /*public synchronized void keyRepeated (int keyCode) {
            int one=1;
        /*    if(keyCode != KEY_POUND && keyCode != KEY_STAR){       
                ConfirmPaint((char)keyCode);
            if (keyCode == 1){
            ConfirmPaint((char)one);
        public synchronized void keyPressed (int keyCode) {
            justPressed=getKeyName(keyCode);
            time=System.currentTimeMillis(); // record the time when the keypress is pressed
            if(justPressed.equals("NUM0")){ //caps lock show indicator .............HERE HERE HERE HERE [1]
                if(poundHit == 0){
                    currentIndicator="ABC";
                    poundHit++;
                    drawIndicator(currentIndicator);
                    //set the string buffer to another one
                if(poundHit == 1){
                    currentIndicator="123";
                    poundHit++;
                    drawIndicator(currentIndicator);
                if(poundHit == 2){
                    currentIndicator="abc";
                    poundHit=0;
                    drawIndicator(currentIndicator);
            if(justPressed.equalsIgnoreCase("SEND")){ //send button allocated as clear button   ................. HERE HERE HERE [2]
                if(sms.length()>0){
                    hidePointer();
                    if(baseline<=10){
                        System.out.println(baseline);
                        line-=2;
                        baseline=(int)width.charAt(line);
                        line++;
                        y_axis-=24;
                    deleteChar();
            if(justPressed.equals("STAR")){//space  ........................................    HERE HERE HERE HERE HERE [3]
                    hidePointer();
                    sms.append(" ");
                    baseline+=white_space;
                    showPointer();
                    prevPressed=justPressed;
            else{
                if(justPressed.equals("NUM1")){index=0;}       
                if(justPressed.equals("NUM2")){index=1;}
                if(justPressed.equals("NUM3")){index=2;}       
                if(justPressed.equals("NUM4")){index=3;}       
                if(justPressed.equals("NUM5")){index=4;}
                if(justPressed.equals("NUM6")){index=5;}
                if(justPressed.equals("NUM7")){index=6;}
                if(justPressed.equals("NUM8")){index=7;}
                if(justPressed.equals("NUM9")){index=8;}
                if(index==0){
                    keypress=true;
                    if(justPressed.equalsIgnoreCase(prevPressed) || dontPrint){
                        if(dontPrint){countPress=35;}
                        if(countPress<34){
                            MyCanvas.ch=keys[index].charAt(countPress);
                            callPaint(MyCanvas.ch);
                            countPress++;
                        else{
                            countPress=0;  
                            MyCanvas.ch=keys[index].charAt(countPress);
                            callPaint(MyCanvas.ch);
                            countPress++;
                        dontPrint=false;
                    else{   //this is executed when the key is not repeated (prev!=)
                            ConfirmPaint(last);
                            countPress=0;  
                            MyCanvas.ch=keys[index].charAt(countPress);
                            callPaint(MyCanvas.ch);
                            countPress++;
                    last=MyCanvas.ch;
                    prevPressed=justPressed;
                if(index==1 || index==2 || index == 3 || index == 4
                || index ==5 || index==7){
                    keypress=true;
                    if(justPressed.equalsIgnoreCase(prevPressed) || dontPrint){
                        if(dontPrint){countPress=4;}
                        if(countPress<3){
                            MyCanvas.ch=keys[index].charAt(countPress);
                            callPaint(MyCanvas.ch);
                            countPress++;
                        else{
                            countPress=0;  
                            MyCanvas.ch=keys[index].charAt(countPress);
                            callPaint(MyCanvas.ch);
                            countPress++;
                        dontPrint = false;
                    else{   //this is executed when the key is not repeated
                            ConfirmPaint(last);
                            countPress=0;  
                            MyCanvas.ch=keys[index].charAt(countPress);                  
                            callPaint(MyCanvas.ch);
                            countPress++;
                    last=MyCanvas.ch;
                    prevPressed=justPressed;
                if(index==6 || index==8){
                    keypress=true;
                    if(justPressed.equalsIgnoreCase(prevPressed)|| dontPrint){
                        if(dontPrint){countPress=5;}
                        if(countPress<4){
                            MyCanvas.ch=keys[index].charAt(countPress);
                            callPaint(MyCanvas.ch);
                            countPress++;
                        else{
                            countPress=0;  
                            MyCanvas.ch=keys[index].charAt(countPress);
                            callPaint(MyCanvas.ch);
                            countPress++;
                        dontPrint=false;
                    else{   //this is executed when the key is not repeated
                            ConfirmPaint(last);
                            countPress=0;  
                            MyCanvas.ch=keys[index].charAt(countPress);
                            callPaint(MyCanvas.ch);
                            countPress++;
                    last=MyCanvas.ch;
                    prevPressed=justPressed;
    /////////////task class for schedule on constructor
    class task extends TimerTask {
        public static boolean bool;
        MyCanvas canvas;
        public task (MyCanvas canvas) {
            this.canvas=canvas;
        public void run () {
            if(canvas.keypress){
                if(System.currentTimeMillis()-canvas.time>150){ //compare the time with the time out
                    canvas.ConfirmPaint(MyCanvas.ch);
                    canvas.counter=-1;
                    canvas.keypress=false;
                    canvas.dontPrint=true;
                    canvas.showPointer();
    }

    Hi I'm writing a program like Multi-tap (the text entry before T9 introduced) on mobilephone.
    I'm having problem with some of the KEYs. They do not work properly.
    As indicated in the code
    HERE HERE [3] suppose to function as space button....However whenever the key is pressed before the 'time out' (I use sceduler to implement the time out) it will print half of the previous character instead of space. this key is not related to the scheduler. so i suspect it is something related to multi-thread programming.
    HERE HERE [1] function as the caps lock. it can even show the indicator properly.... so i need to settle this b4 i continue.
    HEREHERE [2] function as clear button. it doest work too
    Someone please help me....
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package textEntry;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.*;
    import java.util.*;
    * @author Ed's
    public class MyCanvas extends GameCanvas {
        public static final String[] keys =
        {".?!,@`-_:;()&\'\"~10�$��+x*/\\|[]=<>#","abc", "def", "ghi", "jkl",
        "mno", "pqrs", "tuv", "wxyz"};
        public static final String[] capitalKey =
        {".?!,@`-_:;()&\'\"~10�$��+x*/\\|[]=<>#","ABC", "DEF", "GHI", "JKL",
        "MNO", "PQRS", "TUV", "WXYZ"};
        StringBuffer width = new StringBuffer();
        Timer keyTimer;
        textEntryMain main;
        public static char ch;
        public boolean keypress=false;
        public boolean capital;
        public boolean diffrentKey;
        String currentIndicator="abc";
        int countPress=0;
        //int previndex=0;
        public int counter=-1;
        int index=-1;
        int print=0;
        int white_space=6;
        public StringBuffer sms;
        int baseline=10;
        int y_axis=12;
        int line=1;
        char last;
        boolean dontPrint=true; //dont print if timer printed or it is at begining
        Font font;
        Graphics g;
        public long time;
        int poundHit=0;
        String justPressed;
        String prevPressed=null;
        char prevChar;
        //Sms class
        Form smsfrm;
        TextField smsField ;
        //Char Selection speed
        public boolean first;
        int selection_speed=1500;
        //font color (blue)
        public int red=0,green=0,blue=255;
        //Background color (white)
        public int back_red=250,back_green=250,back_blue=250;
        Form menu;
        public MyCanvas(textEntryMain main){
            super(false);
            first=true;
            this.main=main;
            sms=new StringBuffer();
            g=getGraphics();
            font=Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_BOLD,Font.SIZE_LARGE);
            keyTimer = new Timer ();
            keyTimer.schedule (new task (this), selection_speed, selection_speed);
            drawIndicator(currentIndicator);
        public void drawIndicator(String indicator){
            Font f = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_ITALIC, Font.SIZE_SMALL);
            Graphics g = getGraphics();
            g.setFont(f);
            int x= getWidth()-20;
            g.setColor(back_red,back_green,back_blue);
            g.fillRect(x,2,15,10);
            g.setColor(20,20,20);
            g.drawString(indicator, x, 2, g.TOP|g.LEFT);
        public void callPaint(char ch){
            drawIndicator(currentIndicator);
            Graphics g= getGraphics();
            g.setColor(back_red,back_green,back_blue);
            if(first){
                g.fillRect(0,0,getWidth(),getHeight());
                reset();
                redrawAll();
                first=false;
            //baseline -1 so that i can cover the pointer
            g.fillRect(baseline-1,y_axis,font.charWidth(this.last)+3,font.getHeight());
            g.setColor(red,green,blue);
            g.setFont(font);
            g.drawChar(ch,baseline,line*24,g.LEFT|g.BASELINE);
            flushGraphics();
        public void showPointer(){
            Graphics g = getGraphics();
            g.setColor(0,0,0);
            g.drawLine(baseline,y_axis,baseline,2*line*12);
            flushGraphics();
        //pointer appear //pointer disappear-use white line so that it cover the pointer line
        public void hidePointer(){
            Graphics g = getGraphics();
            g.setColor(back_red,back_green,back_blue);
            g.drawLine(baseline,y_axis,baseline,2*line*12);
            flushGraphics();
        //draw the selected
        public void ConfirmPaint(char ch){
            Graphics g = getGraphics();
            sms.append(ch);
            g.setColor(red,green,blue);
            g.setFont(font);
            g.drawChar(ch,baseline,line*24,g.LEFT|g.BASELINE); //draw the selected
            baseline+=font.charWidth(ch); // so that the nect letter won't be drawn on the same position
            if(baseline>getWidth()-30){     //move to the next line
                width.append((char)baseline);
                baseline=10;y_axis+=24;
                line+=1;
            flushGraphics();
        public synchronized void deleteChar(){
            if(sms.charAt(sms.length()-1)==' '){
                baseline-=white_space;
                Graphics g= getGraphics();
                g.setColor(back_red,back_green,back_blue);
                g.fillRect(baseline,y_axis,font.charWidth(sms.charAt(sms.length()-1))+2,font.getHeight());
                sms.deleteCharAt(sms.length()-1);
            else{
                baseline-=font.charWidth(sms.charAt(sms.length()-1));
                Graphics g= getGraphics();
                g.setColor(back_red,back_green,back_blue);
                g.fillRect(baseline,y_axis,font.charWidth(sms.charAt(sms.length()-1))+2,font.getHeight());
                sms.deleteCharAt(sms.length()-1);
            flushGraphics();
        public void redraw(char ch ){
            Graphics g= getGraphics();
            g.setColor(red,green,blue);
            g.setFont(font);
            g.drawChar(ch,baseline,line*24,g.LEFT|g.BASELINE);
            baseline+=font.charWidth(ch);
            if(baseline>getWidth()-30){
                width.append((char)baseline);
                baseline=10;y_axis+=24;
                line+=1;
            flushGraphics();
        public void reset(){
            if(width.length() >0)
            width.delete(0,width.length()-1);
            line=1;
            baseline=10;y_axis=12;
        public void redrawAll(){
            Graphics g=getGraphics();
            g.setColor(back_red,back_green,back_blue);
            g.fillRect(0,0,getWidth(),getHeight());
            reset();
            for(int a=0;a<sms.length();a++)
            redraw(sms.charAt(a));
        /*public synchronized void keyRepeated (int keyCode) {
            int one=1;
        /*    if(keyCode != KEY_POUND && keyCode != KEY_STAR){       
                ConfirmPaint((char)keyCode);
            if (keyCode == 1){
            ConfirmPaint((char)one);
        public synchronized void keyPressed (int keyCode) {
            justPressed=getKeyName(keyCode);
            time=System.currentTimeMillis(); // record the time when the keypress is pressed
            if(justPressed.equals("NUM0")){ //caps lock show indicator .............HERE HERE HERE HERE [1]
                if(poundHit == 0){
                    currentIndicator="ABC";
                    poundHit++;
                    drawIndicator(currentIndicator);
                    //set the string buffer to another one
                if(poundHit == 1){
                    currentIndicator="123";
                    poundHit++;
                    drawIndicator(currentIndicator);
                if(poundHit == 2){
                    currentIndicator="abc";
                    poundHit=0;
                    drawIndicator(currentIndicator);
            if(justPressed.equalsIgnoreCase("SEND")){ //send button allocated as clear button   ................. HERE HERE HERE [2]
                if(sms.length()>0){
                    hidePointer();
                    if(baseline<=10){
                        System.out.println(baseline);
                        line-=2;
                        baseline=(int)width.charAt(line);
                        line++;
                        y_axis-=24;
                    deleteChar();
            if(justPressed.equals("STAR")){//space  ........................................    HERE HERE HERE HERE HERE [3]
                    hidePointer();
                    sms.append(" ");
                    baseline+=white_space;
                    showPointer();
                    prevPressed=justPressed;
            else{
                if(justPressed.equals("NUM1")){index=0;}       
                if(justPressed.equals("NUM2")){index=1;}
                if(justPressed.equals("NUM3")){index=2;}       
                if(justPressed.equals("NUM4")){index=3;}       
                if(justPressed.equals("NUM5")){index=4;}
                if(justPressed.equals("NUM6")){index=5;}
                if(justPressed.equals("NUM7")){index=6;}
                if(justPressed.equals("NUM8")){index=7;}
                if(justPressed.equals("NUM9")){index=8;}
                if(index==0){
                    keypress=true;
                    if(justPressed.equalsIgnoreCase(prevPressed) || dontPrint){
                        if(dontPrint){countPress=35;}
                        if(countPress<34){
                            MyCanvas.ch=keys[index].charAt(countPress);
                            callPaint(MyCanvas.ch);
                            countPress++;
                        else{
                            countPress=0;  
                            MyCanvas.ch=keys[index].charAt(countPress);
                            callPaint(MyCanvas.ch);
                            countPress++;
                        dontPrint=false;
                    else{   //this is executed when the key is not repeated (prev!=)
                            ConfirmPaint(last);
                            countPress=0;  
                            MyCanvas.ch=keys[index].charAt(countPress);
                            callPaint(MyCanvas.ch);
                            countPress++;
                    last=MyCanvas.ch;
                    prevPressed=justPressed;
                if(index==1 || index==2 || index == 3 || index == 4
                || index ==5 || index==7){
                    keypress=true;
                    if(justPressed.equalsIgnoreCase(prevPressed) || dontPrint){
                        if(dontPrint){countPress=4;}
                        if(countPress<3){
                            MyCanvas.ch=keys[index].charAt(countPress);
                            callPaint(MyCanvas.ch);
                            countPress++;
                        else{
                            countPress=0;  
                            MyCanvas.ch=keys[index].charAt(countPress);
                            callPaint(MyCanvas.ch);
                            countPress++;
                        dontPrint = false;
                    else{   //this is executed when the key is not repeated
                            ConfirmPaint(last);
                            countPress=0;  
                            MyCanvas.ch=keys[index].charAt(countPress);                  
                            callPaint(MyCanvas.ch);
                            countPress++;
                    last=MyCanvas.ch;
                    prevPressed=justPressed;
                if(index==6 || index==8){
                    keypress=true;
                    if(justPressed.equalsIgnoreCase(prevPressed)|| dontPrint){
                        if(dontPrint){countPress=5;}
                        if(countPress<4){
                            MyCanvas.ch=keys[index].charAt(countPress);
                            callPaint(MyCanvas.ch);
                            countPress++;
                        else{
                            countPress=0;  
                            MyCanvas.ch=keys[index].charAt(countPress);
                            callPaint(MyCanvas.ch);
                            countPress++;
                        dontPrint=false;
                    else{   //this is executed when the key is not repeated
                            ConfirmPaint(last);
                            countPress=0;  
                            MyCanvas.ch=keys[index].charAt(countPress);
                            callPaint(MyCanvas.ch);
                            countPress++;
                    last=MyCanvas.ch;
                    prevPressed=justPressed;
    /////////////task class for schedule on constructor
    class task extends TimerTask {
        public static boolean bool;
        MyCanvas canvas;
        public task (MyCanvas canvas) {
            this.canvas=canvas;
        public void run () {
            if(canvas.keypress){
                if(System.currentTimeMillis()-canvas.time>150){ //compare the time with the time out
                    canvas.ConfirmPaint(MyCanvas.ch);
                    canvas.counter=-1;
                    canvas.keypress=false;
                    canvas.dontPrint=true;
                    canvas.showPointer();
    }

  • Multi-threaded video decoding problem

    I have simple AIR 3.8 application with 2 VideoPlayers:
    <s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark"
    xmlns:mx="library://ns.adobe.com/flex/mx"
    applicationComplete="init()"
    showStatusBar="false"
    >
    <fx:Script source="MultiVideoPlayer.as" />
    <s:VGroup width="100%" height="100%" >
    <s:HGroup width="100%" height="100%" id="row1" >
    <s:VideoPlayer width="100%" height="100%" source="assets/2.mp4"/>
    <s:VideoPlayer width="100%" height="100%" source="assets/3.mp4"/>
    </s:HGroup>
    </s:VGroup>
    </s:WindowedApplication>
    Both videos are H.264 Full HD samples.
    I launch application and multi-threaded decoding works fine - all cores are involved and CPU usage is around 70%.
    When I replace source of VideoPlayers with exactly same files programmatically - videos are reloading, but they doesn't play smoothly and multi-threaded decoding isn't working anymore - CPU usage drops to 10%.
    Is there any way  to force use of multi-threaded video decoding when videos are loaded dynamically?

    After some hunting I found a Twitter post confirming that StageVideo on AIR 3.2 is not supported on Desktop.
    But one of the notable features of Flash Player 11.2 is Multi-threaded video decoding.
    Does this mean that standard (non-StageVideo) implementations of Video are now automatically using a separate CPU thread?
    If so, this would be a reasonable workaround for smooth video on Desktop.
    Here's Adobe's description of the feature...very vague.
    Multithreaded video decoding (Windows, Mac OS, and Linux) — The video decoding pipeline is now fully multithreaded. This feature should improve the overall performance on all platforms. Note that this feature is a significant architecture change required for other future improvements.

  • SSRS - Is there a multi thread safe way of displaying information from a DataSet in a Report Header?

     In order to dynamically display data in the Report Header based in the current record of the Dataset, we started using Shared Variables, we initially used ReportItems!SomeTextbox.Value, but we noticed that when SomeTextbox was not rendered in the body
    (usually because a comment section grow to occupy most of the page if not more than one page), then the ReportItem printed a blank/null value.
    So, a method was defined in the Code section of the report that would set the value to the shared variable:
    public shared Params as String
    public shared Function SetValues(Param as String ) as String
    Params = Param
    Return Params 
    End Function
    Which would be called in the detail section of the tablix, then in the header a textbox would hold the following expression:
    =Code.Params
    This worked beautifully since, it now didn't mattered that the body section didn't had the SetValues call, the variable persited and the Header displayed the correct value. Our problem now is that when the report is being called in different threads with
    different data, the variable being shared/static gets modified by all the reports being run at the same time. 
    So far I've tried several things:
    - The variables need to be shared, otherwise the value set in the Body can't be seen by the header.
    - Using Hashtables behaves exactly like the ReportItem option.
    - Using a C# DLL with non static variables to take care of this, didn't work because apparently when the DLL is being called by the Body generates a different instance of the DLL than when it's called from the header.
    So is there a way to deal with this issue in a multi thread safe way?
    Thanks in advance!
     

    Hi Angel,
    Per my understanding that you want to dynamic display the group data in the report header, you have set page break based on the group, so when click to the next page, the report hearder will change according to the value in the group, when you are using
    the shared variables you got the multiple thread safe problem, right?
    I have tested on my local environment and can reproduce the issue, according to the multiple safe problem the better way is to use the harshtable behaves in the custom code,  you have mentioned that you have tryied touse the harshtable but finally got
    the same result as using the ReportItem!TextBox.Value, the problem can be cuased by the logic of the code that not works fine.
    Please reference to the custom code below which works fine and can get all the expect value display on every page:
    Shared ht As System.Collections.Hashtable = New System.Collections.Hashtable
    Public Function SetGroupHeader( ByVal group As Object _
    ,ByRef groupName As String _
    ,ByRef userID As String) As String
    Dim key As String = groupName & userID
    If Not group Is Nothing Then
    Dim g As String = CType(group, String)
    If Not (ht.ContainsKey(key)) Then
    ' must be the first pass so set the current group to group
    ht.Add(key, g)
    Else
    If Not (ht(key).Equals(g)) Then
    ht(key) = g
    End If
    End If
    End If
    Return ht(key)
    End Function
    Using this exprssion in the textbox of the reportheader:
    =Code.SetGroupHeader(ReportItems!Language.Value,"GroupName", User!UserID)
    Links belowe about the hashtable and the mutiple threads safe problem for your reference:
    http://stackoverflow.com/questions/2067537/ssrs-code-shared-variables-and-simultaneous-report-execution
    http://sqlserverbiblog.wordpress.com/2011/10/10/using-custom-code-functions-in-reporting-services-reports/
    If you still have any problem, please feel free to ask.
    Regards
    Vicky Liu

  • Memory leaks and multi threading issues in managed client.

    In our company we use a lot of Oracle, and after the release of the managed provider we migrated all applications to it. First the  things were very impressive : the new client was faster, but after some days applications that uses 100MB with old client goes to 1GB and up. The memory is not the only issue, we use a lot of multi threading, and we experience connection drops and not disposal, after 1 days working one of the application had over 100 sessions on the server. I think there is something wrong with connection pool and multi threading.
    Is someone experience same problems.
    Yesterday we went back with unmanaged provider. Now things are back to normal.

    connection drops: did you try to use "Validate Connection=true" parameter in your connection string?
    the new client was faster: are you sure with this statement? Even in 64bit environment? I got quite serious performance problems when running application under 64bit process: https://forums.oracle.com/thread/2595323

  • Multi-thread failure - Error in assignment

    Hello
    I have a c++ program processor running under Windows XP with Oracle 9i. My program access to oracle by an ODBC driver version 9.2.0.4.0. It could be launched in multi-thread to increase performance. When I launch it with one thread everything is fine. When I use several threads I have problems. ODBC driver returns to me a "error in assignment ... General error" message and my updates queries failed. Under SQl server it works without problems. It seems to be a kind of deadlock. When I disable check box in my odbc driver of "enable query timeout" my program encounter a problem and freezes...
    Could someone help me ?

    user13335017 wrote:
    I have thought of the above solutions as workable, however, it is not. Some exhibited errors are:
    A. "Attempt to use database while environment is closed." This error applies to 2, 3 and 4 all the way;
    B. "Attempt to read / write database while database is closed." This error applies to 3 in particular;
    C. "Attempt to close environment while some database is still open." This error applies to 5.
    Please help me with designing a better strategy to solve the concurrent issue. Many thanks in advance.All these are expected errors. You should design the application so that you do not close an environment handle while database handles are still open, keep database handles open for as long as operations need to be performed on the underlying databases, open the database handles after opening the database handles, and close database handles before closing the environment handle.
    In short, in pseudo-code, you should have something like this:
    - open environment handle,
    - open database handles,
    - perform whatever operations are needed on the databases,
    - close database handles,
    - close environment handle.
    You can refer to the Getting Started with Data Storage and the Getting Started with Transaction Processing guides appropriate for the API you are using, from the Berkeley DB documentation page.
    Regards,
    Andrei

  • Multi-Threaded server using  ThreadPool

    Dear friends,
    I am writing a client-server program in which the client and server communicate using SUN-RPC. The client reads a file containing some numbers and then spawns threads which it uses to request the server for a service. These threads are executed using a thread pool. Till this time, it's working fine. But when it comes to the server, the real trouble begins because it too needs to be made a multi-threaded one using thread pooling. The server has to capture the call information for each request for the service and then pass this information to a thread/runnable object in whose run() method the code for execution of the service would be present. Since the tasks(requests for the service) are not present already, i am unable to execute the server side threads in a loop using a thread pool. How to solve this problem? Kindly help.
    Thanks,
    Subhash

    The server has to capture the call information for each request for the serviceWhy?
    and then pass this information to a thread/runnable object in whose run() method the code for execution of the service would be present.Why can't the run() method get the call information when it starts? That's what's normally done. The server's accept loop mustn't do any other I/O: otherwise a rogue client can block the server complete.y

  • Multi-Thread application and common data

    I try to make a multi-Thread application. All the Threads will update some common data.
    How could I access the variable �VALUE� with the Thread in the following code:
    public class Demo {
    private static long VALUE;
    public Demo(long SvId) {
    VALUE = 0;
    public static class makeThread extends Thread {
    public void run() {
    VALUE++;
    public static long getVALUE() {
    return VALUE;
    The goal is to get the �VALUE� updated by the Thread with �getVALUE()�
    Thanks for your reply
    Benoit

    That code is so wrong in so many ways......
    I know you're just experimenting here, learning what can and can't be done with Threads, but bad habits start early, and get harder to kick as time goes on. I am going to give a little explanation here about what's wrong, and what's right.. If you're going to do anything serious though, please, read some books, and don't pick up bad habits.
    Alright, The "answer" code. You don't use Thread.sleep() to wait for Threads to finish. That's just silly, use the join() method. It blocks until the threads execution is done. So if you have a whole bunch of threads in an array, and you want to start them up, and then do something once they finish. Do this.
    for(int k=0; k<threads.length; k++) {
      threads[k].start();
    for(int k=0; k<threads.length; k++) {
      threads[k].join();
    System.out.println("All Threads Done");Now that's the simple problem. No tears there.
    On to the java memory model. Here where the eye water starts flowing. The program you have written is not guarenteed to do what you expect it to do, that is, increment VALUE some amount of time and then print it out. The program is not "Thread Safe".
    Problem 1) - Atomic Operations and Synchronization
    Incrementing a 'long' is not an atomic operation via the JVM spec, icrementing an int is, so if you change the type of VALUE to an int you don't have to worry about corruption here. If a long is required, or any method with more then one operation that must complete without another thread entering. Then you must learn how to use the synchronized keyword.
    Problem 2) - Visiblity
    To get at this problem you have to understand low level computing terms. The variable VALUE will NOT be written out to main memory every time you increment it. It will be stored in the CPUs cache. If you have more then one CPU, and different CPUs get those threads you are starting up, one CPU won't know what the other is doing. You get memory overwrites, and nothing you expect. If you solve problem 1 by using a synchronized block, you also solve problem 2, because updating a variable under a lock will cause full visiblity of the change. However, there is another keyword in java.. "volatile".. A field modified with this keyword will always have it's changes visible.
    This is a very short explaination, barely scratching the surface. I won't even go into performance issues here. If you want to know more. Here's the resources.
    Doug Lea's book
    http://java.sun.com/docs/books/cp/
    Doug Lea's Site
    http://g.cs.oswego.edu
    -Spinoza

  • Thread problems - shutting down.

    Okay, I've got my multi-threaded server program working just fine and all is well...until I shut down the server.
    By some quirky twist of fate, java chat servers seem to be a popular education assignment in the last two weeks, which will probably put some people off answering this simply because of all the clueless posts on the subject recently. :)
    Anyway, a little background on how I'm doing things first.
    At the top there is the Server object, which is implementing Runnable. This instances the ClientManager, creates the ServerSocket and then kicks off its own thread and loops in the run() method waiting for connections while a boolean is true. If it gets a connection it calls the ClientManager addConnection() method and passes it the received client socket.
    The ClientManager holds a List of ClientConnections and provides methods to add and remove ClientConnections. The ClientManager also runs in its own thread by implementing the Runnable interface and uses its run() method to loop through checking for incoming messages from each client.
    A ClientConnection object also runs in its own thread via the Runnable interface. This checks for incoming messages from the client and stores the String ready to be received by the ClientManager and broadcast to all ClientConnections.
    So, you've got the Server running in its own thread, the ClientManager running in its own thread and the ClientManager maintaining a List of ClientConnections, each running in its own thread.
    I'm starting my threads like this:-
    // Constructor.
    Public SomeObject() {
        start();
    // Runnable method.
    Public void start() {
        // threadObject is private class variable.
        bThreadActive = true;
        this.threadObject = new Thread(this);
        threadObject.setDaemon(true);
        threadObject.start();
    }I'm running my threadded object like this: -
    Public void run() {
        do {
            // Do work here.
        } while(bThreadActive);
        // Activates the shutdown method for this object.
        shutdownObject();
    }I'm shutting down my threads like this: -
    Public void shutdown() {
        this.bThreadActive = false;
    // The main shutdown code.
    Public void shutdownObject() {
        // Kill thread object.
        this.threadObject = null;
        // Do other stuff.
    }Which I think should work fine. Anything wrong with the above?
    I'm getting problems with NullPointerExceptions with the Server object at the point where it tries to shutdown the ClientManager. This works by shutting down all ClientConnections in the List first and then emptying the List before killing its own thread. Also, the Server object seems to shutdown before the ClientManager. And other such weirdness.
    I know you're all going to ask for specific code and a stacktrace, which I'll provide....I just want to check that my method for using threads as above is correct first, so I can rule that out - mostly because I suspect I'm missing some vital piece of knowledge on using threads....things are not working as I expect.
    Anyway, a quick answer on the above and then I'll start posting more specific info.
    Thanks all :)

    Ooops....my mistake. I was calling shutdown() twice. Once from the GUI code and automatically from after the loop in the run() method. Funny how the stacktrace doesn't drill down any further than the method that makes this call.
    Okay, its almost all working perfectly, except for this part....
        //  Start accepting client connections from the server service.
        public void run() {
             while(bThreadActive) {
                 if (sockServer != null) {
                     if (!sockServer.isClosed()) {
                         try {
                             sockClient = sockServer.accept();
                             if (sockClient != null) {
                                 this.clientManager.addClientConnection(sockClient);
                                 this.pOutput.printOutput("Connection accepted from: " + sockClient.getInetAddress().getHostAddress());
                         } catch (IOException ioe) {
                             if (bThreadActive) {
                                 this.pOutput.printOutput("ERROR: Could not accept incoming client connection");
                         } catch (NullPointerException npe) {
                             // Leave this for now.
             shutdown();
        // Shutdown the server service and disconnect all client connections.
        public void shutdown() {
            try {
                clientManager.stopThread();
                sockServer.close();
                threadServer = null;
            } catch (NullPointerException npe) {
                npe.printStackTrace();
            } catch (IOException ioe) {
                pOutput.printOutput("ERROR: Could not cleanly shutdown the server socket");
            pOutput.printOutput("Server service shut down successfully");
        // Stop the server thread (automatically shuts down).
        public synchronized void stopThread() {
            bThreadActive = false;
        }When I call the above like this from the GUI object...
        // Stop the server.
        private void stopServer() {
             try {
                  server.stopThread();
                  setGUIMode(MODE_DISCONNECTED);
             } catch (NullPointerException npe) {
                  npe.printStackTrace();
        }...the string "Server service shut down successfully" from the completion of the shutdown() method never appears, so it looks as though its not executing.
    But if I do this instead in the stopServer() method and remove the shutdown() call in the run() method, it works......but I get two (sometimes three) outputs of "Server service shut down successfully" which makes me think its being run twice somehow.....once before the ClientManager has been shutdown and once after or twice after.
    Server service shut down successfully
    Shutting down Client Manager...
    All client connections disconnected
    Client Manager successfully shutdown
    Server service shut down successfully
    Server service shut down successfully
    Any ideas?

  • InfoPath: the multi-threading challenge

    Or to be more specific: calling a DataSource from a different thread.
    A project I'm working on includes an InfoPath form in which some heavy duty tasks are executed. These tasks can take over 10+ seconds to execute. To avoid the GUI to get stuck during execution, multi-threading is implemented. The problem lies in providing
    feedback to the user. Several methods have been used, but all end in the exceptions shown below.
    Unlike WinForms and such, InfoPath does not seem to provide a way to invoke the GUI. What we are trying to do is change field values to reflect the status of the process. This is done through the MainDataSource. I've tried several methods to call
    this datasource through another thread, like invoking a provided delegate, or execution context. However all these methods have similar results.
    When calling a method or property on the datasource the following exception is thrown:
    System.InvalidOperationException was unhandled
      Message="Operation is not valid due to the current state of the object."
      Source="Microsoft.Office.InfoPath.Client.Internal.Host"
      StackTrace:
           at Microsoft.Office.Interop.InfoPath.SemiTrust.ICLRExtensionsWrapper.IncrementSqmPoint(Int32 idDataPt)
           at Microsoft.Office.InfoPath.Internal.DataSourceHost.CreateNavigator()
           at Form1.FormCode.ContextCallbackMethod(Object obj) in E:\Projects\InfoPath Multithreading\Source\Form1\FormCode.cs:line 74
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at Form1.FormCode.ThreadMethod(Object myParamsObj) in E:\Projects\InfoPath Multithreading\Source\Form1\FormCode.cs:line 68
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart(Object obj)
    This seems to indicate the DataSource is locked for some reason. Even the ReadOnly property can not be read.
    When calling the SetValue method on an XPathNavigator provided by a datasource and passed through another thread, the following exception is thrown:
    System.AccessViolationException was unhandled
      Message="Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
      Source="Microsoft.Office.InfoPath.Client.Internal.Host.Interop"
      StackTrace:
           at Microsoft.MsoOffice.InfoPath.MsxmlInterop.NativeHelpers.SetText(IXMLDOMNode* , Char* )
           at Microsoft.MsoOffice.InfoPath.MsxmlInterop.MsxmlNodeImpl.set_Text(String strText)
           at Microsoft.Office.InfoPath.MsxmlNavigator.SetValue(String value)
           at Form1.FormCode.DelegateMethod(XPathNavigator nav) in E:\Projects\InfoPath Multithreading\Source\Form1\FormCode.cs:line 81
           at Form1.FormCode.ThreadMethod(Object myParamsObj) in E:\Projects\InfoPath Multithreading\Source\Form1\FormCode.cs:line 70
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart(Object obj)
    I have searched through the internet but am unable to find any useful information about this subject. There are only a few weeks remaining before the deadline. A work-around has been implemented, but since it requires additional active user interaction
    it is far from ideal. I hope you can help me in finding a solution.

    For anyone who is still interested all this time later....
    I wouldn't use a Dispatcher in InfoPath simply because InfoPath requires .Net 2.0 only and Dispatcher was not added until .Net 3.0 which means you would have to enforce installation of .Net 3.0 yourself.
    There is an easy alternative which is SynchronizationContext (more specifically a WindowsFormsSynchronizationContext).
    Also I suggest you do not use ThreadStart but rather use one of the more modern and well known threading paradigms. A good alternative is a BackgroundWorker.
    e.g.
    private BackgroundWorker _Worker;
    public void InternalStartup()
    InitializeWorker();
    ((ButtonEvent)EventManager.ControlEvents["Button"]).Clicked += new ClickedEventHandler(ButtonClick);
    public void InitializeWorker()
    _Worker = new BackgroundWorker();
    _Worker.WorkerReportsProgress = true;
    _Rorker.WorkerSupportsCancellation = true;
    _Worker.DoWork += new DoWorkEventHandler(_Worker_DoWork);
    _Worker.ProgressChanged += new ProgressChangedEventHandler(_Worker_ProgressChanged);
    _Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_Worker_RunWorkerCompleted);
    public void ButtonClick(object sender, ClickedEventArgs e)
    if (_Worker.IsBusy)
    _Worker.CancelAsync();
    else
    // Very important to include this line!
    AsyncOperationManager.SynchronizationContext = new WindowsFormsSynchronizationContext();
    _Worker.RunWorkerAsync();
    void _Worker_DoWork(object sender, DoWorkEventArgs e)
    // Do stuff in another thread and report back to the UI thread.
    object state;
    int percentage = 0;
    _Worker.ReportProgress(percentage, state).
    public void _Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    // This is called on the thread that started the worker.
    // In this case the UI thread which means it is safe to use the MainDataSource.
    CreateNavigator().SelectSingleNode("my:Main/my:Progress", NamespaceManager).SetValue(e.ProgressPercentage);
    void _Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    // Do anything you want to do on completion here.
    One thing of note is that the SynchronizationContext in InfoPath for some reason or other always seems to be Null. The result is that when you call RunWorkerAsync() it captures the current synchronization context (null) which means the default is used and
    a ProgressChanged is called on a new thread each time. To prevent this we need to manually set the context before calling RunWorkerAsync() which is done using the AsyncOperationManager.

Maybe you are looking for

  • UCCX 8.0 - 1st node crashed

    Hi, We have a 2-server UCCX 8.0 cluster running on UCS servers. Recently, when moving the publisher (1st node) to a new UCS server, we accidently deleted some files of the Virtual machine. (there are 2 folders in the datastore, named UCCX1 and UCCX1_

  • Instantiating a Custom Component

    I am somewhat new to this concept and I keep thinking about things the ActionScript 2 way where we can say: createObject(refObject,instanceName,depth,constructorObject); I am instantiating custom MXML components using a technique similar to the follo

  • My MacBook is having problems with one CD (driver is okay?)

    The CD doesn't start playing for about 15 seconds after inserting. It sounds like my computer is having a hard time reading it. What can be the problem??? ALL other CD's are running perfectly. Message was edited by: that was my alias

  • SAP Netweaver XI Basis...

    Hey, Can nybody give me the most useful documents for learnng SAP Netweaver XI Basis. Cheers., Xeon

  • Basic Data Types as Class Objects

    Consider the following code using the java.lang.reflect.Method Class c = Class.forName("java.util.Date"); // get all methods in Date Method[] c_classes = c.getMethods(); // get the UTC method - UTC(int year, int month, int date, int hrs, int min, int