Multi threaded programming

I am quite new to multi threaded programming.
The problem I am facing in my code is as follows:
I can instantiate 1-10 threads from my controller class. For example if my controller class generates 10 threads, 5 threads
finish the task they are assigned to do(i.e send SMS and Update the Database) and the other 5 threads eventhough send SMS but
get stuck when they are supposed to update the Database (this is inferred from the logs).
Due to this problem my controller class remains in a wait state as I am using the join() method and some of the threads never
join.
Another interesting observation is that it always happens that the thread numbered 0-5 always get stuck at the exact point
where database has to be updated and thread number 6-10 complete their task. Same is the case when i instantiate 2 threads, i
thread completes its task and another thread gets stuck, again at the same point.
I am using Connection Pooling to connect to the database.
I am sure that the problem is with the query
int j=dbObject.execute_pst("UPDATE table SET flag='true' WHERE message IN("+trueFlag+")",con);
where true flag is a comma seperated string containing some ID's.
What i cannot understand is why some of the threads (almost 50% of them), work fine with this query and the others get stuck
(i.e. just wait at this query during runtime)

The problem must lie in the connection, as the SQL statement is to basic to cause an endless loop inside the DBMS. If you are in doubt, try the setMaxRows() method of the Statement interface, I'm using Sybase and it also limits the number of rows processed in update and delete statements (which I'm pretty sure is buggy, but you can still try it).
Which DBMS are you using by the way?

Similar Messages

  • Running a Java Multi Thread Program in database

    I have created a multi threaded program in Java and it runs successfully from the command prompt. I want to create a DBMS Job which will wake up at regular intervals and runs the java program(Java stored procedure). Is this possible in 9.2/10G ?? If Yes, will there be any impact on the DB performance/increase memory etc.,
    The database (9.2...) resides on a RH 2.3 AS box.
    Any ideas...
    Thanks,
    Purush

    Purush,
    Java stored procedures cannot be multi-threaded. Well, they can, but the threads will not run in parallel. You may be able to find some more information in the Oracle documentation, which is available from:
    http://tahiti.oracle.com
    Good Luck,
    Avi.

  • HELP!....GUI crashes when i call a multi-threaded program from it

    Hi..I have encountered a problem in my end of year project, which i cant see to solve. The problem is i am starting a multi-threaded program for a JButton on a GUI. All though this starts the other program it crashes the GUI completely how do i stop this.
    this is the code i use to call the threaded program.
    public void actionPerformed(ActionEvent e)
    Object target=e.getSource();
    String line = new String();
    if( target==b1 )
         try
    cl = new client();
         cl.startup();
         catch(Exception ex){ex.printStackTrace();}
    thanks Mike

    No there is no exceptions being given. this is one of the reasons why i dont no what to do. i thought myself that the threaded was taking all the resources and not going back to the GUI. if this is the case is there anyway that i can call back the GUI and keep the threaded program running?
    thanks
    mike.

  • Multi-threaded program hangs in Linux with green thread when doing I/O

    Hi,
    I am using green thread(jdk1.3.1) on Linux. My program is in multi-threaded model and has some I/O operations. I am runing one java program using Runtime.exec("java <program>"). Actually the <program> prompts user with some question like "enter location" and waits for the input. Now in my code I am constantly reading the input stream of the process. Once I get the string like "enter location", immediately I send the location through Process o/p stream. But the process is not able to read this and hangs there for ever.
    Please help, what could be the problem? If you need the source code, pls let me know.
    Thanks in advance,
    Sisir

    I had a similar issue few weeks back... If I could see the source I would have a better understanding of the problem and think I could help out. If you want to send it, send it to [email protected]
    thanks,
    JP

  • Long running multi threaded programs on 2.6

    Hi,
    Will there be any problem, if a multi-threaded appl is running for long time.
    New thread ids were over 50,000,000.
    Program started behaving strangely after a month's run. Restarting it works fine.
    any thoughts.
    Thanks
    Mega

    That stipulation has ALWAYS existed and applies to the entire suite.
    I doubt anyone is bust your door down, however.
    Bob

  • Example multi-thread program

    Hi,
    Can anybody tell me where can I find a multi-thread (THREADED_MUTEXED) occi example?
    Thanks in advance,
    Jose LUIs.

    Hi,
    Can anybody tell me where can I find a multi-thread (THREADED_MUTEXED) occi example?
    Thanks in advance,
    Jose LUIs.

  • LocalReport.Render freezes in multi thread program

    I have a program that is trying to render multiple PDF's asynchronously using the task object. For each iteration, I create a new task object that will call a method that also instantiate a new LocalReport object. The problem occurs when I try to render
    the report using LocalReport.Render(). It just freezes there without any errors. Even when there is only 1 task created, the LocalReport.Render just freezes.
    When using LocalReport.Render outside of a task object, it works fine and I was able to generate a PDF.

    The exact same rules for multithreading apply to both static and non-static methods--if the method accesses any shared variables that might be accessed by another thread, and if you need atomicity or need threads to see each others' updates of those variables, then you need to synchronize.
    In your particular example, there are no shared variables, so it doesn't matter.

  • Multi-thread programming

    Hi!
    I'd like to know what happens if I defined a class a singleton and diffrent threads are going to using it. Are they workin' with only one instance of that class or each of the thread creates own copy of singleton?
    If they workin only with one instance of that class probbably such situation can lead to some misbehaviour, inst it?
    What kind of situation are the most suitable for applaing singleton classes
    Greatly appreciate any help!!!

    What kind of situation are the most suitable for
    applaing singleton classes For example to ensure certain things are only initialized once (like a huge data file loaded into a cache).
    And to channel the access to certain data (e.g. a 'global' counter) so that everyone in the process is really talking about the same thing. Of course if you don't synchronize the access to these data you cannot be sure that it stays in a correct state while different threads sew over it.

  • MUlti-threading concept

    Hi All,
    Want to know how we can multi-thread a program for a particular PLSQL code in Oracle EBS for which the child thread doesn't consume any thread in the front-end even though it executes with user-specified threads?

    Hi;
    Please review below notes which could gives you some idea:
    How Does iPayment Use Multi Threading? [ID 983478.1]
    http://orabiz.blogspot.com/2010/06/ebs-plsql-multithreading-example.html
    Can I have multi-thread program in EBS
    Regard
    Helios

  • Using nanosleep() in a threaded program cause SIGBUS or SIGSEGV

    Greetings,
    I'm working on a multit-threaded program using Solaris' threads (not POSIX).
    When I call nanosleep() or usleep(), sometimes the program works well, but often I get either a SIGSEGV or a SIGBUS.
    Have a look at the following dbx output using a core file:
    (dbx) threads
    o>    t@1  a  l@1   ?()   signal SIGSEGV in  t_splay()
          t@2  a  l@2   cpu_thread()   LWP suspended in  ___nanosleep()
    (dbx) thread 2
    dbx: unrecognized arg/option '2'
    Use the 'help' command for more information.
    (dbx) thread t@2
    Current function is cpu_thread
      367           nanosleep(&sleep_time, NULL);
    t@2 (l@2) stopped in ___nanosleep at 0xfe5c017c
    0xfe5c017c: ___nanosleep+0x0008:        bcc,a,pt  %icc,___nanosleep+0x18       ! 0xfe5c018c
    (dbx) list
      367           nanosleep(&sleep_time, NULL);
    (dbx)The code used to create the thread:
    thr_create(NULL, 0, cpu_thread, NULL, 0, &tid);Am I missing something?
    Any suggestions are welcome.
    Thanks,
    -Thomas

    t@1 a l@1 ?() signal SIGSEGV in t_splay() Most likely a corrupted malloc heap. Thread t@1 is crashing
    somewhere inside malloc() or free().
    Use libumem(3LIB) or dbx's access / memory checking support
    to find out where you're corrupting the malloc heap.
    t@2 a l@2 cpu_thread() LWP suspended in ___nanosleep() The nanosleeping thread isn't responsible for the crash.
    The t@1 thread is the culprit. Print a stack trace for thread t@1.

  • Some general questions about multi-threading

    Hey Everybody,
    I have a dilemma with a multi-threaded program that I have written.
    Well to be truthful I actually wrote the program with no consideration whatsoever for multithreading.
    As a result of this complete lack of concern I get a completely hung user interface.
    My program performs a lot of network communications over URL��s and also writes information from URL��s to disk. The combination of networking and I/O in my program and the fact that I have not built multi-threading into the program has lead to complete failure of the user interface. When I say complete failure I mean complete failure. If it were only button��s not responding then I wouldn��t be all that worried, however the entire drawing area of my programs ��Frame�� completely freezes. It��s cool if nothing is maximized or minimized over the frame but as soon as this happens my programs drawing area has a ��serious hang over!��.
    I have begun learning about threads, in principle they sound wicked however in practice they have proven to be a brain tease (oops �K.. honesty).
    The difficulty of threads should not be all that daunting to me, however I have a couple of very simple questions that I would love to have answered�K..anybody out there!!!!!!!!!
    This is the normal basic method of running a thread that I have been attempting to incorporate into my program:
    1). Extend the thread class,
    2). Override the run() method in the subclass (created from step 1),
    3). Create an instance of the subclass,
    4). Call the start() method on the instance (from step 3).
    I have read that every statement the thread will execute is contained within it��s run() method.
    Question 1). This being the case is it possible to have member variables or methods inside a class that extends thread? Please explain!
    Question 2). Can a class that extends thread contain a constructor? Please explain!
    Question 3). If a subclass of thread cannot contain a constructor as I assume to be the case then how can code executing within the newly spawned thread reference information from the object that spawned it?
    If anybody out there on the great net can answer even half of one of these questions I will be more than grateful. Thanks for your time, and rock on Java!
    David

    Thread t = new Thread(MyRunnableDerivedClass);
    t.start();I hope it is understood that MyRunnableDerivedClass is actually an object of the MyRunnableDerivedClass. sorry for the confusion.
    so here's a thread that reads from a file using constructors, member variables, other funcs. It's not optimal but shows use of all of the above. I just typed this in so there are probably syntax errors, but you should get the point.
    public class ThreadedFileReader implements Runnable
        private File m_File;
        byte[] contents = new byte[0];
        public ThreadedFileReader( File f )
           m_File = f;
        public void run()
            BufferedInputStream bis = null;
            try
                bis = new BufferedInputStream( new FileInputStream( m_File ));
                int avail = bis.available();
                while (avail > 0)
                    int oldLen = contents.length();
                    contents = expand( contents, avail );
                    bis.read( contents, oldLen, avail );
                    avail = bis.available();
            catch (Exception e)
            { //do something witty
            finally
                try{ if (bis != null) bis.close(); } catch (Exception e){}
       private byte[] expand( byte[] oldBuf, int addedLen )
          byte[] newBuf = new char[oldBuf.length + addedLen];
          System.arrayCopy( newBuf, 0, oldBuf, 0, oldBuf.length );
          return newBuf;
       public byte[] getContents()
           return contents;
    //here's where we use it
    File f = new File( "c:\myfile" );
    ThreadedFileReader tfr = new ThreadedFileReader( f );
    Thread t = new Thread( tfr );
    t.start();
    t.join();
    // At this point the thread has died, but the thread object still exists
    byte [] data = tfr.getContents();

  • Multi-thread BackgroundWorker

    Hi, 
    Is BackgroundWorker a recommended way to write a multi-threading application? If not, what is the preferred way for multi-threading programming?
    Thanks in advance!

    Thanks for the comments.
    Below is the scenario:
    A main application is monitoring any incoming files in a network folder.
    Whenever a new file turns up, application will start a BackgroundWorker to process the file.
    There may be many files constantly go to this folder
    Q: do I need to create a BackgroundWorker for each individual file?
    Thanks for your help.

  • Simple multi thread example

    Hello I am still confused as to how to run parallel processes. I am looking for something very simple so that I can understand better. If possible I would like to see an example that basically starts a vi that writes to a file. For example the vi has a for loop that runs 10 times each time it generates a new instance of a program that writes the number associated with the for loop to the file 2 times. So basically after the program is run the file will read.1122334455667788991010...or have some numbers mixed up depending on how fast each thread ran. I guess the vi would have some controls on the front to adjust the number of times so that the user could get the idea of how the threads would end up writing of order...This is a common example similar to "hello world" of multi threading programs in most languages so I figured that there would be something like this somewhere...but I can't find it. If anyone can point me in the right direction I would appreciate it thanks.

    Hmmm. I cannot locate a good example for you, but I know it's possible.
    So I created my own example  (I THINK I saved it in 8.5 format)
    YOU NEED TO HANDLE ERRORS - this example doesn't.
    But it does do what you asked.
    It spawns any number of subVIs, all of which run independently. 
    Steve Bird
    Culverson Software - Elegant software that is a pleasure to use.
    Culverson.com
    Blog for (mostly LabVIEW) programmers: Tips And Tricks
    Attachments:
    Spawning.llb ‏39 KB

  • Helpful hint while multi-threading

    Hi all
    This had me stupmed for a little while. A multi-threaded program I'd been working didn't appear to be working correctly. I noticed this was because it looked like the thread never made it to its run() method. The cause of this was the fact id overridden the start() method of the thread without including this.run() at the end. The symptoms of this happening aren't obvious though, and it can be quite puzzling. I hope this gets added to any FAQs etc, or solves someones problem.

    And if, for whatever reason, you do need to override start(), you should not call this.run() at the end, you should call super.start() !!!
    If you call this.run() at the end, you are having the current thread go and do the run method.

  • 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();
    }

Maybe you are looking for