Return of thread starting new method

hi,
I have an application that runs a thread pool, each thread builds up a linklist. what I need to know is that I Need to get this linklist only when the thread is done and pass it to another method in another object where all of these linklists are kept.
How do I do this, I dont have a huge knowledge on threads :(
I believe I can add this new objective ( to keep all the linklists ) to be run in the same thread pool as well or should I make a new seperate thread to run it.
Other thing is I believe I can synchronize that method so it waits until one link list is finished, but is this an efficient way I mean the threads in my thread pool changes fast, so is it ok to make the method synchronized. I mean does that decrease the performance, say each thread takes about 1 sec to finish...
Thank you.

thanks
each thread is for obtaining information from network
stream which takes up time. one thread handles one
IP. If I use only 1 thread It takes a hell of a long
time.. I said 1 sec for 1 thread as just a measure
but practically it takes more than that ...Okay. I just wanted to make sure you had a good reason to use multiple threads, rather than thinking that multithreading a CPU-intensive operation would magically make it go faster.
I'll try the join method, the main thread which
starts the thread pool execution waits until
everything is done.That can work, depending on your requirements. If you want the main thread to stop and do nothing until ALL the other threads are done, that's fine. But if you want something to happen as soon as each thread finishes, join is not a good way to go.
so is it OK if I run the linklist
processing method in the mainthread's stack or shall
I use a thread in the thread pool for that..I don't understand enough about what you're trying to do to answer that.

Similar Messages

  • Thread start() method problem

    I have a program server-client program that have a lot thread but
    when I called thread.start() method it doesn't return run() method.
    even so my input-output codes is running ( my client program can send data to server program )
    Please help me

    yasinmalli wrote:
    start() method doesn't call run() method of thread when I debug row to rowIt does, but the debugger will only ever follow the flow of the current thread and therefore not step into the run method. Set a breakpoint at the very beginning of your run() method and then step over the start() method, you'll see that the new thread will break exactly at that breakpoint just after start() was executed.

  • Starting new threads from within shutdown hooks

    I'd like to discuss this statement from the java 6 API:
    "A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. *When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt*. Note that daemon threads will continue to run during the shutdown sequence, as will non-daemon threads if shutdown was initiated by invoking the exit method. "
    Now, my question is this: If I have a hook that starts a new non-daemon thread and then goes on to complete it's run() method, will the JVM finalize and halt? Or will it wait for my new thread to complete as well?
    I trust the specification, and believe that the JVM will either not allow me to create the thread or will finalize and shutdown even if it is running. However it's not explicitly stated anywhere, and I think that it's a hole in the documentation.
    I'm going to write a test case for this now. But chime in if you have thoughts.

    This is what happens if you start a new thread from a shutdown hook and do not wait for it to finish:
    public class ShutdownTest {
        private static class Shutdownhook extends Thread{
            public void run() {
                System.out.println("Shutdownhook starting");
                Thread t = new Thread(){
                    public void run(){
                        System.out.println("Thread successfully started");
                        try{ Thread.sleep(5000); }
                        catch(Throwable e){ System.out.println("Throwable from sleep: "+e); }
                        System.out.println("Thread successfully finished");
                t.start();
                //try {t.join();} catch (InterruptedException e) {}
                System.out.println("Shutdownhook completing");
        public static void main(String[] args) {
            Runtime.getRuntime().addShutdownHook(new Shutdownhook());
            System.out.println("Exiting from main()");
            Runtime.getRuntime().exit(0);
    Exiting from main()
    Shutdownhook starting
    Shutdownhook completing
    Thread successfully startedHowever, as you might expect, if you join() or wait for the thread's isAlive() to return false, you will be able to complete the thread.
    I'll leave someone else to figure out if that new thread gets finalized and if finalizers on exit is on, what happens. Mostly because it doesn't matter for my purposes.
    Enjoy

  • Starting new threads from a servlet

    Hi
    I read somewhere that starting new threads from a servlet is not supported in the future releases of J2EE .
    Any one aware of this.
    I have a listener program started as a new thread from the init method of a servlet which is set to load on startup.
    I have to think about another way to do this if this is not suppported in the future releases
    any comments

    Dr clap
    Actually I was getting some warning messages in my websphere server console when I tried to make JDBC connections from the thread I opened in the servlet.
    Everthing works fine but with the warning messages,
    Then someone from IBM answered me in one of the forums quote
    Cause: These messages are being produced due to an
    "unsupported" environment. When application is
    spinning its own threads from an EJB, spinning a
    thread and accessing a database is not supported (per
    the J2EE specification). One exception to this rule is
    if a Servlet is spinning its own threads and accessing
    a database. The J2EE specification is not clear on
    this, so WebSphere Application Server 5.0 must allow
    for it at this time. IBM is working with Sun to
    clarify this in the specification, so eventually (i.e.
    J2EE 1.4) spun threads from a Servlet accessing a
    database outside of a transaction will not be
    supported either.
    Since we don't want to promote the usage of these
    "naked" threads accessing databases, we are producing
    the warning messages. Although they may be filling up
    the logs, we feel that these are necessary to warn the
    user that they are doing something not in-line with
    the intended usage. Customer should consider changing
    their application to comply with the
    J2EE specification.
    """

  • Return Code value using 'starting new task' and 'wait until'

    I'm having a minor issue with some return code values in my ABAP.
    This is what part of it used to look like before I modified it:
    With Code in version 1, the sy-subrc was not always zero, sometimes it would be 4.
    That was fine, and my abap would do something based on the non-zero RC.
    had a need to implement an RFC timeout, the only way I could see to do it was to use 'starting new task' etc as seen in Version 2.
    However, with my changes, sy-subrc is always zero.
    The ABAP runs fine but I know that sy-subrc should sometimes be 4, even when it returns within the allotted 60 seconds.
    Maybe I've coded it incorrectly.
    Can someone point me in the right direction?
    #>> Start of VERSION 1
      call function 'MY_FUNCTION_MODULE'
           destination RFCDEST
           tables
                orders_list          = t_orders_packet
                apo_orders_list      = t_apo_orders
                apo_resources        = t_apo_resources
           exceptions
                COMMUNICATION_FAILURE    = 1 MESSAGE MSG_TEXT
                SYSTEM_FAILURE           = 2 MESSAGE MSG_TEXT
                NO_ORDERS_SUPPLIED       = 3
                NO_PEGGED_ORDERS_FOUND   = 4
                ORDERID_CONVERSION_ERROR = 5
                OTHERS                   = 6.
    if sy-subrc is initial.
      * do some stuff as RC was 0
    else.
    * log non-zero return code etc
    endif.
    * << End of Version 1

    And now Version 2.
    I didn't put this into the 1st post as the formatting goes bonkers.
    #>> Start of VERSION 2
      call function 'MY_FUNCTION_MODULE'
           destination RFCDEST
           starting new task 'taskname'
           performing receive_result on end of task
           tables
                orders_list          = t_orders_packet
                apo_orders_list      = t_apo_orders
                apo_resources        = t_apo_resources
           exceptions
                COMMUNICATION_FAILURE    = 1 MESSAGE MSG_TEXT
                SYSTEM_FAILURE           = 2 MESSAGE MSG_TEXT
                NO_ORDERS_SUPPLIED       = 3
                NO_PEGGED_ORDERS_FOUND   = 4
                ORDERID_CONVERSION_ERROR = 5
                OTHERS                   = 6.
      WAIT UNTIL results_received = 'X' UP TO 60 SECONDS.
    if sy-subrc is initial.   << Now this is always ZERO
      * do some stuff as RC was 0
    else.
    * log non-zero return code etc
    endif.
    FORM receive_result USING iv_taskname.
      RECEIVE RESULTS FROM FUNCTION 'MY_FUNCTION_MODULE'
           tables
                orders_list          = t_orders_packet
                apo_orders_list      = t_apo_orders
                apo_resources        = t_apo_resources
           exceptions
                COMMUNICATION_FAILURE    = 1 MESSAGE MSG_TEXT
                SYSTEM_FAILURE           = 2 MESSAGE MSG_TEXT
                NO_ORDERS_SUPPLIED       = 3
                NO_PEGGED_ORDERS_FOUND   = 4
                ORDERID_CONVERSION_ERROR = 5
                OTHERS                   = 6.
      results_received = 'X'.
    endform.                    "receive_result
    * < End of Version 2

  • How to view source of native method Thread.start()

    I have already downloaded and unzipped the source code for JDK. I want to view the implementation of Thread.start() method. However, I can only see one line:
    public synchronized native void start();Could anyone tell me how can view the implementation of this method? And generally, how can I view the implementation of a native method?
    Regards,
    Xinjun

    %SRC_BASE%\j2se\src\share\native\java\lang\Thread.c,
    but that only defines a table in which start0()
    forwards you to JVM_StartThread(), wherever that may
    be.You are crossing the boundary between the JDK code and the JVM (Java Virtual Machine). If you have unpacked the Mustang sources [1], take a look at:
    hotspot/src/share/vm/prims/jvm.cpp lines 2421 through 2504.
    This will soon lead you to hotspot/src/share/vm/runtime/thread.cpp
    Hope this helps...
    [1] https://mustang.dev.java.net/

  • Thread Callable call() method question

    i am using callable interface and i need to return from call() method before process gets over.
    basically i have infinite loop in call() method which gets data from streaming services,
    and once i format the data and send back to EDT to update UI constantly.
    i am using call() method because my call() (same as run() runnable) throws exception if there is any problem in receiving data.
    i don't care for return value from call(). i only care if there is any exception.
    if i don't do task.get().... then everything works fine, but then i dont get any executionException as well, (which i really care for)
    FutureTask<String> task = new FutureTask<String>(resParser);
    Thread thread= new Thread(task);
    thread.start();
    try{
        String result = task.get();
    }catch(ExecutionException e){
        e.printStackTrace();
    }catch(InterruptedException ex){
    }any solution ??
    Thanks

    You will need to re-consider your requirements. You either call get() and block the active thread, or you let the thread continue to run and don't call get().
    Your solution would be to catch the exception someplace else and feed the exception (or message) to wherever you need it. Why do you think you need to catch the exception right here (which is apparently in your EDT)? Why not catch it in the Thread's run method and deal with it there?

  • When my thread starts running, at that time keylistener is not working.

    when my thread starts running, at that time keylistener is not working.
    plz reply me.

    //FrameShow.java
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import java.awt.Dimension;
    import java.awt.geom.Dimension2D;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import java.util.logging.Level;
    import java.awt.event.*;
    import java.util.*;
    public class FrameShow extends JFrame implements ActionListener,KeyListener
         boolean paused=false;
         JButton stop;
         JButton start;
         JButton exit;
         public IncludePanel CenterPanel;
         public FrameShow()
    CenterPanel= new IncludePanel();
              Functions fn=new Functions();
              int height=fn.getScreenHeight();
              int width=fn.getScreenWidth();
              setTitle("Game Assignment--Santanu Tripathy--MCA");
              setSize(width,height);
              setResizable(false);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              show();
              initComponents();
              DefaultColorSet();
              this.addKeyListener(this);
         this.setFocusable(true);
         public void initComponents()
              Container contentpane=getContentPane();
              //Creating Panel For Different Side
              JPanel EastPanel= new JPanel();
              JPanel WestPanel= new JPanel();
              JPanel NorthPanel= new JPanel();
              JPanel SouthPanel= new JPanel();
              //CenterPanel = new IncludePanel();
              //IncludePanel CenterPanel= new IncludePanel();
              EastPanel.setPreferredSize(new Dimension(100,10));
              WestPanel.setPreferredSize(new Dimension(100,10));
              NorthPanel.setPreferredSize(new Dimension(10,100));
              SouthPanel.setPreferredSize(new Dimension(10,100));
              //CenterPanel.setPreferredSize(new Dimension(200,200));
              //Adding Color to the Panels
              NorthPanel.setBackground(Color.green);
              SouthPanel.setBackground(Color.orange);
              CenterPanel.setBackground(Color.black);
              //Creating Border For Different Side
              Border EastBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border WestBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border NorthBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border SouthBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border CenterBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              //Creating Components For East Panel
              JLabel left= new JLabel("LEFT");
              JLabel right= new JLabel("RIGHT");
              JLabel rotate= new JLabel("ROTATE");
              left.setForeground(Color.blue);
              right.setForeground(Color.blue);
              rotate.setForeground(Color.blue);
              //Creating Components For West Panel
              ButtonGroup group = new ButtonGroup();
              JRadioButton rb1 = new JRadioButton("Pink",false);
              JRadioButton rb2 = new JRadioButton("Cyan",false);
              JRadioButton rb3 = new JRadioButton("Orange",false);
              JRadioButton _default = new JRadioButton("Black",true);
              rb1.setForeground(Color.pink);
              rb2.setForeground(Color.cyan);
              rb3.setForeground(Color.orange);
              _default.setForeground(Color.black);
              //Creating Components For North Panel
              JLabel name= new JLabel("Santanu Tripathy");
              name.setForeground(Color.blue);
              name.setFont(new Font("Serif",Font.BOLD,30));
              //Creating Components For South Panel
              start = new JButton();
              stop = new JButton();
              exit = new JButton();
              start.setToolTipText("Click this button to start the game");
              start.setFont(new java.awt.Font("Trebuchet MS", 0, 12));
              start.setText("START");
              start.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(3, 5, 3, 5), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
              start.setMaximumSize(new java.awt.Dimension(90, 35));
              start.setMinimumSize(new java.awt.Dimension(90, 35));
              start.setPreferredSize(new java.awt.Dimension(95, 35));
              if(paused)
                   stop.setToolTipText("Click this button to pause the game");
              else
                   stop.setToolTipText("Click this button to resume the game");
              stop.setFont(new java.awt.Font("Trebuchet MS", 0, 12));
              stop.setText("PAUSE");
              stop.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(3, 5, 3, 5), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
              stop.setMaximumSize(new java.awt.Dimension(90, 35));
              stop.setMinimumSize(new java.awt.Dimension(90, 35));
              stop.setPreferredSize(new java.awt.Dimension(95, 35));
              exit.setToolTipText("Click this button to exit from the game");
              exit.setFont(new java.awt.Font("Trebuchet MS", 0, 12));
              exit.setText("EXIT");
              exit.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(3, 5, 3, 5), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
              exit.setMaximumSize(new java.awt.Dimension(90, 35));
              exit.setMinimumSize(new java.awt.Dimension(90, 35));
              exit.setPreferredSize(new java.awt.Dimension(95, 35));
              //Adding some extra things to the Panels
              group.add(rb1);
              group.add(rb2);
              group.add(rb3);
              group.add(_default);
              //Adding Component into the Panels
              EastPanel.add(left);
              EastPanel.add(right);
              EastPanel.add(rotate);
              WestPanel.add(rb1);
              WestPanel.add(rb2);
              WestPanel.add(rb3);
              WestPanel.add(_default);
              NorthPanel.add(name);
              SouthPanel.add(start);
              SouthPanel.add(stop);
              SouthPanel.add(exit);
              //Adding Border Into the Panels
              EastPanel.setBorder(EastBr);
              WestPanel.setBorder(WestBr);
              NorthPanel.setBorder(NorthBr);
              SouthPanel.setBorder(SouthBr);
              CenterPanel.setBorder(CenterBr);
              //Adding Panels into the Container
              EastPanel.setLayout(new GridLayout(0,1));
              contentpane.add(EastPanel,BorderLayout.EAST);
              WestPanel.setLayout(new GridLayout(0,1));
              contentpane.add(WestPanel,BorderLayout.WEST);
              contentpane.add(NorthPanel,BorderLayout.NORTH);
              contentpane.add(SouthPanel,BorderLayout.SOUTH);
              contentpane.add(CenterPanel,BorderLayout.CENTER);
              //Adding Action Listeners
              rb1.addActionListener(this);
              rb2.addActionListener(this);
              rb3.addActionListener(this);
              _default.addActionListener(this);
              exit.addActionListener(this);
              start.addActionListener(this);
    try
              start.addActionListener(
    new ActionListener() {
    public void actionPerformed( ActionEvent e )
                        start.setEnabled(false);
    CenterPanel.drawCircle();
    catch(Exception e)
    {System.out.println("Exception is attached with sart button exp = "+e);}
    try
              stop.addActionListener(
    new ActionListener() {
    public void actionPerformed( ActionEvent e )
                        paused=!paused;
                        if(paused)
                             start.setToolTipText("Click this button to resume the game");
                             stop.setText("RESUME");
                        else
                             start.setToolTipText("Click this button to pause the game");
                             stop.setText("PAUSE");
    CenterPanel.pause();
    catch(Exception e)
    {System.out.println("Exception is attached with sart button exp = "+e);}
         public void DefaultColorSet()
              getContentPane().setBackground(Color.white);
         public void actionPerformed(ActionEvent AE)
              String str=(String)AE.getActionCommand();
              if(str.equalsIgnoreCase("pink"))
                   CenterPanel.setBackground(Color.pink);
              if(str.equalsIgnoreCase("cyan"))
                   CenterPanel.setBackground(Color.cyan);
              if(str.equalsIgnoreCase("orange"))
                   CenterPanel.setBackground(Color.orange);
              if(str.equalsIgnoreCase("black"))
                   CenterPanel.setBackground(Color.black);
              if(str.equalsIgnoreCase("exit"))
                   System.exit(0);
         public void keyTyped(KeyEvent kevt)
    //repaint();
    public void keyPressed(KeyEvent e)
              System.out.println("here key pressed");
              //CenterPanel.dec();
         public void keyReleased(KeyEvent ke) {}
    }//End of FrameShow.ja
    //IncludePanel.java
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.Graphics.*;
    import java.awt.Dimension;
    import java.awt.geom.Dimension2D;
    import java.util.*;
    import java.util.logging.Level;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    public class IncludePanel extends JPanel implements Runnable
    int x=0,y=0;
    int color_1=0;
    int color_2=1;
    int start=0;
    Thread th;
    Image red,blue,green,yellow;
    java.util.List image;
    static boolean PAUSE=false;
         public IncludePanel()
         red= Toolkit.getDefaultToolkit().getImage("red.png");
         blue= Toolkit.getDefaultToolkit().getImage("blue.png");
         green= Toolkit.getDefaultToolkit().getImage("green.png");
         yellow= Toolkit.getDefaultToolkit().getImage("yellow.png");
    public void paintComponent(Graphics g)
              super.paintComponent(g);
              draw(g);
    public void dec()
         System.out.println("in dec method");
         x=x+30;
    public void draw(Graphics g)
              g.setColor(Color.red);
              int xx=0,yy=0;
              for (int row=0;row<=12;row++)
                   g.drawLine(xx,yy,180,yy);
                   yy=yy+30;
              xx=0;
              yy=0;
              for (int col=0;col<=6;col++)
                   g.drawLine(xx,yy,xx,360);
                   xx=xx+30;
              if(color_1==0)
                   g.drawImage(red, x, y, this);
              else if(color_1==1)
                   g.drawImage(blue,x, y, this);
              else if(color_1==2)
                   g.drawImage(green,x,y, this);
              else if(color_1==3)
                   g.drawImage(yellow,x,y, this);
    x=x+30;
              if(color_2==0)
                   g.drawImage(red, x, y, this);
              else if(color_2==1)
                   g.drawImage(blue,x,y, this);
              else if(color_2==2)
                   g.drawImage(green,x,y, this);
              else if(color_2==3)
                   g.drawImage(yellow,x,y, this);
    x=0;
    public void drawCircle( )
         th=new Thread(this);
         th.start();
         public void pause()
              if(PAUSE)
                   th.resume();
                   PAUSE=false;
                   return;
              if(!PAUSE)
              PAUSE=true;
         public synchronized void run()
              Random rand = new Random();
              Thread ani=Thread.currentThread();
              while(ani==th)
                   if(PAUSE)
                        th.suspend();
                   if(y==330)
                        color_1 = Math.abs(rand.nextInt())%4;
                        color_2 = Math.abs(rand.nextInt())%4;
                        if(color_1==color_2)
                             color_2=(color_2+1)%4;
                        y=0;
                   else
                        y=y+30;
                   repaint();
                   try
                        Thread.sleep(700);
                   catch(Exception e)
         }//End of run
    i sent two entire program

  • One thread starts one does not

    hello
    still i'm learning threads.
    i've got an applet "pingpong".
    there are two threads
    1. pingThread pt
    2. Thread sammelThread
    pingthread makes some int-values
    sammelThread collects them and repaints the applet.
    i've got 2 problems:
    1. -- sammelthread does not start
    2. -- if paint() gets the right value, (see commented line in paint())it does not repaint the rectangle
    the source:
    public class pingThread extends Thread{
         private int hoehe = 10;
         private boolean up = true;
         public void run(){
                            while(true){
                                    if (isInterrupted()){
                                            break;
                                    }//if
                                    if (up){
                                            hoehe = hoehe +10;
                                            if (hoehe == 200){
                                                    up = false;
                                            }//if
                                    }else{
                                            hoehe = hoehe -10;
                                            if (hoehe == 10){
                                                    up = true;
                                            }//if
                                    }//if-else
                                    System.out.println("hoehe/up: " + hoehe + ", " +up);
                                    try {
                                            Thread.sleep(400);
                                    } catch (InterruptedException e) {
                                            interrupt();
                            }//while
                    }//run
                    public int gethoehe(){
                            System.out.println(" und nun :  gethoehe() = " +hoehe);
                            return hoehe;
    }//class
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Graphics;
    public class pingpong extends java.applet.Applet implements Runnable, ActionListener{
            Button btn;
            pingThread pit = new pingThread();
            Thread sammelThread;
            int pinghoehe;
            public void init() {
                    setLayout (new FlowLayout() );
                    btn = new Button("Stop");
                    btn.addActionListener(this);
                    add(btn);
                    setVisible(true);
                    pit.start();
                    repaint();
            }//init()
            public void actionPerformed(ActionEvent event){
            Object obj = event.getSource();
                    if (obj == btn){
                            System.out.println("Button : Stop");
                            pit.interrupt();
            }// actionPerformed
            public void paint(Graphics g){
                     //zum testen:
                     //pinghoehe = pit.gethoehe();
                    System.out.println("paint - pinghoehe = " +pinghoehe);
                    g.fillRect(10,pinghoehe, 5, 5);
            public void start(){
                    System.out.println("pingpong - start");
                    if (sammelThread == null){
                            sammelThread = new Thread();
                            System.out.println("pingpong - start -start");
                            sammelThread.start();
            }//start
            public void stop(){
                    if (sammelThread != null) {
                            sammelThread = null;
            }//stop
            public void run(){
                    System.out.println("sammelthread.run()");
                    while(true){
                            pinghoehe = pit.gethoehe();
                            System.out.println("sammelthread - pinghoehe = " +pinghoehe);
                            repaint();
                    }//while
            }//run
    } //pong()

    With
    sammelThread = new Thread();
    sammelThread.start();
    you are creating a new Thread, which will do nothing.
    If you want to call the run-method of your own Runnable "pingpong" (better with uppercase "Pingpong", because it's a classname!), you have to write:
    sammelThread = new Thread(this);
    sammelThread.start();
    The method start of sammelThread will call the run-method of the Runnable this (pingpong).

  • Starting new database LUW inside ABAP during IDoc posting

    Hi all,
    During posting of an inbound IDoc, I am trying to update my Z-table in user-exit. I want to do it regardless of the result of IDoc posting. The problem is: if IDoc posted successfully - table is updated because COMMIT WORK is called at the end of the posting, however, if IDoc not posted - ROLLBACK WORK is called and table is not updated. So, my aim now is to commit the update of Z-table in any case, but it is the only thing that should be committed - no other prior update FMu2019s should be committed.
    I'm aware about the following thread
    http://forums.sdn.sap.com/thread.jspa?threadID=1884700
    Author of this thread says that he solved a problem by means of RFC and STARTING NEW TASK. But ABAP help says
    that starting asynchronous RFC triggers immediately a database commit in the calling program (which is unacceptable because all prior update FMu2019s will be committed ). I've checked and it is really the case.
    From my point of view SET UPDATE TASK LOCAL with COMMIT WORK should work in such kind of tasks, but in case of IDoc processing the whole process runs in a local update (see SET UPDATE TASK LOCAL in FM 'IDOC_INPUT'), so writing once again SET UPDATE TASK LOCAL has no effect.
    I tested SUBMIT statement as well. It had no effect and then I found out from ABAP help that SUBMIT ... AND RETURN starts new SAP LUW, but NOT a DB LUW. That is if I update my Z-table in the program called by SUBMIT - all ROLLBACK statements still affect my  Z-table update.
    Is there any simple solution? Please suggest.
    Thanks in advance!

    Hello,
    Try SUBMIT VIA JOB.....
    Sample Code
    call function 'JOB_OPEN'
    exporting
    jobname = name
    importing
    jobcount = number
    exceptions
    cant_create_job = 1
    invalid_job_data = 2
    jobname_missing = 3
    others = 4.
    if sy-subrc = 0.
    submit z_idoc_create_process_order and return
    via job name number number
    with p_aufnr = it_header1-aufnr
    with p_werks = it_header1-werks
    with p_autyp = c_autyp
    with p_auart = it_header1-auart
    with p_dispo = it_header1-dispo
    with p_opt = c_opt
    with p_mestyp = c_mestyp.
    if sy-subrc = 0.
    call function 'JOB_CLOSE'
    exporting
    jobcount = number
    jobname = name
    strtimmed = 'X'
    exceptions
    cant_start_immediate = 1
    invalid_startdate = 2
    jobname_missing = 3
    job_close_failed = 4
    job_nosteps = 5
    job_notex = 6
    lock_failed = 7
    others = 8.
    if sy-subrc 0.
    endif.

  • When we create JDialog inside Thread's run() method it is creating problem

    I have application that has feature that mainframe will be locked after three minutes and the time when it is locked it will show other locked dialog.
    Now my problem is given below:
    I have created one Dialog inside Threads run() method and this thread will execute when mainframe is locked.So what is happening is when mainframe is locked internally Thread is doing its job (its job is to display one dialog) and it is displaying dialog but mainframe is locked and still it is showing that dialog.This should not happen in our application when mainframe is locked nothing should come outside.
    simple code sample is given below:
    SwingUtilities.invokeLater(new Runnable()
    JDailog dlg = new JDialog();
    dlg.pack();
    dlg.show();
    Now when my applications mainframe is locked and thread is doing its job when mainframe is locked and it will show one dialog when its run() method will execute and it showing dialog even though mainframe is locked.This is major issue for me.please help me.
    sample code may contain compile errror but this only to give understanding what i am doing actually i cant show my original code.
    But show me some work around for this problem.Why dialog is coming outside when mainframe is locked?
    Please help me.I cant use delay inside run() method because of performance.
    Is there any way to control this behaviour?

    public class BackGroundThread extends javax.swing.JFrame implements BackgroundTaskInf {
        boolean isMainWindowActive = false;
        /** Creates new form BackGroundThread */
        public BackGroundThread() {
            initComponents();
            new DBBackgroudProcess(this).start();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            jDialog1 = new javax.swing.JDialog();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jButton1 = new javax.swing.JButton();
            jLabel1.setText("JOB DONE");
            javax.swing.GroupLayout jDialog1Layout = new javax.swing.GroupLayout(jDialog1.getContentPane());
            jDialog1.getContentPane().setLayout(jDialog1Layout);
            jDialog1Layout.setHorizontalGroup(
                jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jDialog1Layout.createSequentialGroup()
                    .addGap(95, 95, 95)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(240, Short.MAX_VALUE))
            jDialog1Layout.setVerticalGroup(
                jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jDialog1Layout.createSequentialGroup()
                    .addGap(22, 22, 22)
                    .addComponent(jLabel1)
                    .addContainerGap(22, Short.MAX_VALUE))
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jLabel2.setText("Background work in progess");
            jButton1.setText("unlock");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(56, 56, 56)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(126, Short.MAX_VALUE))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(263, Short.MAX_VALUE)
                    .addComponent(jButton1)
                    .addGap(74, 74, 74))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(40, 40, 40)
                    .addComponent(jLabel2)
                    .addGap(37, 37, 37)
                    .addComponent(jButton1)
                    .addContainerGap(43, Short.MAX_VALUE))
            pack();
        }// </editor-fold>                       
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            isMainWindowActive = true;
            backgroundTaskFinished();
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new BackGroundThread().setVisible(true);
        public void backgroundTaskFinished(){
            if(isMainWindowActive) {
                jDialog1.setSize(200,200);
                jDialog1.setVisible(true);
                jLabel2.setText("Task is finished");
        // Variables declaration - do not modify                    
        private javax.swing.JButton jButton1;
        private javax.swing.JDialog jDialog1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        // End of variables declaration                  
    class DBBackgroudProcess extends Thread {
        BackgroundTaskInf infObj;
        public DBBackgroudProcess(BackgroundTaskInf infObj){
            this.infObj = infObj;
        public void run(){
            try{
                // here you can do your backgroudn task
                System.out.println("In BackGroud task");
                Thread.sleep(1000);
                System.out.println("task completed");
                infObj.backgroundTaskFinished();
            }catch(Exception e){
                e.printStackTrace();
    interface BackgroundTaskInf{
        public void backgroundTaskFinished();
    }

  • STARTING NEW TASK

    can ny 1 give me a simple example as to WHY call function STARTING NEW TASK is used ???
    i need a very very simple example to demonstrate the concept

    hi there...
    Syntax
    CALL FUNCTION func STARTING NEW TASK task
                  DESTINATION {dest
                  parameter list
                  {PERFORMING subr}.
    Additions:
    1. ...DESTINATION IN GROUP { group |DEFAULT}
    2. ...{PERFORMING subr}|{CALLING meth} ON END OF TASK
    Effect
    Asynchronous call of a remote-capable function module specified in func using the RFC interface. You can use the addition DESTINATION to specify a single destination in dest, or to specify a group of application servers by using IN GROUP. The latter supports parallel processing of multiple function modules. The calling program is continued using the statement CALL FUNCTION, as soon as the remotely called function has been started in the target system, without having to wait for its processing to be finished. You can use PERFORMING and CALLINGto specify callback routines for copying results when the remotely called function is finished. Character-type data objects are expected for func and dest.
    If the destination has not been specified, the destination NONE is used implicitly. When the destination NONE is used, a new main session is opened for the current user session. The asynchronous RFC does not support communication with external systems or programs written in other programming languages.
    A character-type data object must be specified for task, one which contains for the remotely called function module a freely definable task ID that has a maximum eight digits. This task ID must be unique for each call, and is handed to the callback routines for identifying the function. Each task ID defines a separate RFC connection with its own context, meaning that, in the case of repeated function module calls of the same task ID, the global data of the relevant function group can be accessed, if the connection still exists.
    In dialog processing, note that the maximum number of six main sessions cannot be exceeded, else an error message is displayed.
    Addition 1
    ... DESTINATION IN GROUP {group|DEFAULT}
    Effect
    Specifying IN GROUP as a destination allows you to execute multiple function modules in parallel on a predefined group of application servers in the current SAP system.
    For group, you must specify a data object of the type RZLLI_APCL from the ABAP Dictionary, one that is either initial, or one that includes the name of an RFC server group created in transaction RZ12. When specifying DEFAULT, or if group is initial, all application servers that are currently available in the current SAP system are used as a group. Only one RFC server group may be used within a program. During the first asynchronous RFC using the addition IN GROUP, the specified RFC server group is initialized. For each asynchronous RFC where the group is specified, the most suitable application server is determined automatically, and the called function module is executed on this.
    If the function module cannot be executed on any application server, due to not enough resources being currently available, this leads to the predefined exception RESOURCE_FAILURE, to which a return value can be assigned, in addition to the remaining RFC exceptions. For this exception, the addition MESSAGE is not permitted.
    ·        The parallel processing of function modules using the addition IN GROUP makes optimum use of the resources available, and is preferred to self-programmed parallel processing with destinations that are specified explicitly.
    ·        An application server that is used as part of an RFC server group for parallel processing must have at least three dialog work processes, of which one is currently free. Other resources such as requests in the queue, number of system logons and so on, are also taken into account, and are not allowed to exceed certain limit values.
    ·        To ensure that only those application servers that have enough resources are accessed, we recommend that you work with explicitly defined RFC server groups instead of working with the addition DEFAULT.
    ·        The function modules of the function group SPBT provide service functions for parallel processing, for example, initialization of RFC server groups, determining the used destination, or temporarily removing an application server from an RFC server group.
    Addition 2
    ... {PERFORMING subr}|{CALLING meth} ON END OF TASK
    Effect
    You can use this addition to specify either a subprogram subr or, as of Release 6.20, a method meth as a callback routine, which is executed after the asynchronously called function module has finished. For subr, you have to directly specify a subprogram of the same program. For meth, you can enter the same details as for the general method call.
    The specified subprogram subr can have exactly one SING parameter of type clike only. The method meth must be public, and can have only one non-optional input parameter p_task of type clike. When the RFC interface is called, this parameter is supplied with the task ID of the remotely called function that was specified in the call in task. The results of the remote function can be received in the subprogram subr or method meth using the statement RECEIVE. In the callback routine, no statements can be executed that cause the program run to terminate or end an SAP LUW. Statements for list output are not executed.
    Prerequisite for executing a callback routine is that, after the remote function has ended, the calling program is still internally available. It is then executed the next time the work process is changed. If the program has ended, or if it is part of a call sequence in the stack, then the callback routine is not executed. The statement WAIT can be used to stop the program execution until certain or all callback routines have been executed.
    CALL FUNCTION - STARTING NEW TASK parameter_list
    Syntax
        [EXCEPTIONS exc1 = n1  exc2 = n2 ...
    Effect
    These additions are used to assign actual parameters to the formal parameters of the function module, and return values to exceptions that are not class-based. These additions have the same meaning as for the synchronous RFC. The only exception is that no values can be copied with IMPORTING and CHANGING.
    do reward if helpful

  • Thread.start() without run() invoke

    We got interesting problem during migration one old application from java 1.4.2_08 to the java 1.5.0_06. The principal code of application is:
    public class objServ extends Thread {
      public void run() {
         while (!End) {
               clientSocket = ServSocket.accept();
               client = new objClient(this, clientSocket);
               logger.sendInfo("client created. "+client.getName());
               client.start();
               logger.sendInfo("client start done. "+client.getName());
      public static void main(String args[]) {
          pkvserv serv = new objServ(hostName, port);
          serv.start();
    public class objClient extends Thread {
       // client method run()
      public void run() {
         printlog("Thread run started. "+this..getName());
    }The application listen port and generate the client thread for each connection.
    After 10 days of using this application and generating and successful processing and termination of near 340000 client threads we got a situation when client thread was created, method start() was invoked, but the client method run() was never invoke.
    Does anybody have any idea why this situation can happen? We have memory monitoring on that application and it�s was not a memory problem.

    So you're claiming there's a bug in the VM. I doubt it (at least not one of the nature you're claiming). I'd suspect your code didn't execute start(), or that if it did, run() did execute and you're making a faulty conclusion that it didn't.

  • Cannot start JavaFX Task using Thread.start()

    Well I am currently studying JavaFX and as a total beginner(but not in Java) I started reading the official tutorials in Java and I'm currently studying Concurrency in JavaFX. and I tried to create my first JavaFx Task Object and start it. This what I have tried so far
    package concurrency;
    import javafx.concurrent.Task;
    public class JavaTaskClass {
          * @param args
         public static void main(String[] args) {
              //create task object
              Task<Integer> task = new Task<Integer>(){
                   @Override
                   protected Integer call() throws Exception{
                        System.out.println("Background task started...");
                        int iterations;
                        for(iterations = 0; iterations < 10000; iterations++){
                             if(isCancelled()){
                                  break;
                             System.out.println("Iteration " + iterations);
                             Thread.sleep(3000);
                        return iterations;
              //start the background task
              Thread th = new Thread(task);
              th.setDaemon(true);
              System.out.println("Starting background task...");
              th.start();
    but the task doesn't start. I don't see any messages in my console. Is there something I missed?
    Edited by: 979420 on Jan 1, 2013 10:02 PM
    Edited by: 979420 on Jan 1, 2013 10:02 PM
    Edited by: 979420 on Jan 1, 2013 10:03 PM
    Edited by: 979420 on Jan 1, 2013 10:49 PM

    Tasks are meant to be run in the context of a JavaFX application, like in the example below:
    import javafx.application.Application;
    import javafx.concurrent.Task;
    import javafx.scene.Scene;
    import javafx.scene.layout.StackPane;
    import javafx.scene.paint.Color;
    import javafx.stage.Stage;
    import java.io.IOException;
    public class TaskApp extends Application {
      public static void main(String[] args) { launch(args); }
      @Override public void start(final Stage stage) throws IOException {
        //create task object
        Task<Integer> task = new Task<Integer>(){
          @Override
          protected Integer call() throws Exception{
            System.out.println("Background task started...");
            int iterations;
            for(iterations = 0; iterations < 10000; iterations++){
              if(isCancelled()){
                break;
              System.out.println("Iteration " + iterations);
              Thread.sleep(3000);
            return iterations;
        //start the background task
        Thread th = new Thread(task);
        th.setDaemon(true);
        System.out.println("Starting background task...");
        th.start();
        stage.setScene(new Scene(new StackPane(), 200, 100, Color.BLANCHEDALMOND));
        stage.show();
    }Also your code was setting the task thread as a daemon thread. The Java Virtual Machine exits when the only threads running are all daemon threads. So once your main routine finished (which would be really quickly), the program would just exit without doing anything much. Note that, in your example, even if you made the Task thread a non-daemon thread, it still doesn't work (likely because the Task class has some reliance on the JavaFX system being initialized). For your simple background process you could skip Task and just use a Runnable or a Callable (which doesn't require JavaFX and hence would work in a non-daemon thread invoked from main), but I guess it's just an experiment.

  • Thread's run method

    I cannot unserstand why the output of this program is:
    axa axa
    class A extends Thread
    public void run()
    System.out.print("axa ");
    public class Main
    public static void main(String[] args) throws Exception
    Thread t = new Thread(new A());
    t.run();
    t.start();

    Guestios wrote:
    Why the
    t.run();
    calls the run() method of the Class A?
    t is just an instance of class ThreadThe implementation of the run() method in the Thread class looks like this:
    public void run() {
         if (target != null) {
             target.run();
    }The 'target' variable is the Runnable you passed to the Thread in the constructor, which was an instance of A, so it's run() method was called.
    Jim S.

Maybe you are looking for

  • How can I remove my old phone?

    I recently got a new Iphone 4 and wonder how I can remove the profile for the 3Gs in Itunes? It still shows up in such things as Find my Iphone and such.

  • Final Cut Studio 2 Render Times Exponetianlly  Greater

    Used to have Final Cut Studio, loved it, render times were very reasonable, I upgraded 2 weeks ago to Final Cut Studio 2 and the render times are not outrageous. What used to take 5-10 minutes to render is 3 hours or so. Am I missing something?

  • PDF exports look terrible - white lines in text

    I have been u sing indesign for years and years all of the sudden my pdf exports look terrible. The images are pixelated and the text has white lines in it. I used these pdf previews for my clients and I certainly cant use what Im getting from INDD r

  • Find every responsibility with access to function

    Hi, When they setup Applications here they went a little nuts with custom responsibilities and menus. Of course there's no doc :( Has anyone found/written SQL to determine all responsibilities with access to a given (forms) function ? Oracle's report

  • ITunes Requires Safari 4.0.3

    Hi - When I try to go to iTunes store in iTunes 9, I get a message that says: iTunes requires Safari 4.0.3 or later to be installed to use the iTunes Store within iTunes. Use Software Update to download and install the latest version of Safari. I tri