Qestion for implementing Runnable

HI,
I have a function which executes multiple methods and store the result from those methods in List<Stirng> before the last methods executes I need to insert these List<String> values in a database with my dao object.
I was wondering if I do the following:
new Thread(new myInsertWorker()).start();
executeMyFunction();
Would I improve the performance on my program since it is very important for this last function to be fast.
My question is if I insert the strings as a separate thread how do I need to write the thread to be as simple as possible and not cause any performance issues?

Here is my code, I am new to concurrent programming, therefore I move slowly :) and check my code with someone else to prevent issues I am not aware of.
Can I improve this simple piece of code to make sure if it does fail or hangs my application will not be affected?
Thank you
public class LogMessageWorker implements Runnable {
    List<LogMessage>_messages = new LinkedList();
    LogMessageDAO _logMessageDAO=null;
    public LogMessageWorker(LogMessageDAO logMessageDAO, List<LogMessage> messages){
        this._messages = messages;
        this._logMessageDAO = logMessageDAO;
    public LogMessageWorker(LogMessageDAO logMessageDAO, LogMessage message){
        this._messages.add(message);
        this._logMessageDAO = logMessageDAO;
    public void run() {
        try{
            _logMessageDAO.add(_messages);
        }catch(Exception e){
            e.printStackTrace();
}This is how I call it:
try {
            Thread logMsgThread = new Thread(new LogMessageWorker(logMessageDAO, logMessages));
            //logMsgThread.setPriority(Thread.MIN_PRIORITY);
            logMsgThread.start();
        } catch (Exception e) {
            e.printStackTrace();
        }Edited by: kminev on Dec 3, 2009 2:06 PM

Similar Messages

  • Threads: implement runnable or extend Thread.  Which is better?

    I want to know which way is better, as I want to do some work in threads.
    Thanks,
    Virum

    I want to know which way is better, as I want to do
    some work in threads.
    Thanks,
    VirumOne reason for implementing runnable can be that java doesnot allow multiple inheritance so by implementing runnable you can, at the same time, extend another class.
    Another reason though not recommended and not good programming practice is that although you cannot restart a dead thread, if you use runnables, you can submit the old runnable instance to a new thread, thus practically starting a thread more than once.

  • Question about methods in a class that implements Runnable

    I have a class that contains methods that are called by other classes. I wanted it to run in its own thread (to free up the SWT GUI thread because it appeared to be blocking the GUI thread). So, I had it implement Runnable, made a run method that just waits for the thread to be stopped:
    while (StopTheThread == false)
    try
    Thread.sleep(10);
    catch (InterruptedException e)
    //System.out.println("here");
    (the thread is started in the class constructor)
    I assumed that the other methods in this class would be running in the thread and would thus not block when called, but it appears the SWT GUI thread is still blocked. Is my assumption wrong?

    powerdroid wrote:
    Oh, excellent. Thank you for this explanation. So, if the run method calls any other method in the class, those are run in the new thread, but any time a method is called from another class, it runs on the calling class' thread. Correct?Yes.
    This will work fine, in that I can have the run method do all the necessary calling of the other methods, but how can I get return values back to the original (to know the results of the process run in the new thread)?Easy: use higher-level classes than thread. Specifically those found in java.util.concurrent:
    public class MyCallable implements Callable<Foo> {
      public Foo call() {
        return SomeClass.doExpensiveCalculation();
    ExecutorService executor = Executors.newFixedThreadPool();
    Future<Foo> future = executor.submit(new MyCallable());
    // do some other stuff
    Foo result = future.get(); // get will wait until MyCallable is finished or return the value immediately when it is already done.

  • Reflect the class that implements Runnable

    Hi,
    I am implementing the reflection of the class that implements Runnable. In order to start a new thread I am trying to invoke "start()" method ( which is obviously not defined my class ) and I therefore I am getting "java.lang.NoSuchMethodException".
    I am wondering is it possible at all to start a new thread on a reflected class?
    thanks in advance.
    {              Class refClass = Class.forName(className);
    String methodName = "start";
    Class[] types = new Class[1];
    types[0] = Class.forName("java.util.HashMap");
    Constructor cons = refClass.getConstructor(types);
    Object[] params = new Object[5];
    params[0] = new HashMap();
    Method libMethod = refClass.getMethod(methodName, null);
    libMethod.invoke(objType, null); }

    Well, if we knew what it meant to "start a thread on a class" we could probably figure out how to "start a thread on a reflected class". If we knew what a "reflected class" was, that is.
    In other words, it would help if you rephrased your question using standard terminology (and also explained why you want to do whatever it is you want to do).
    But let's guess for now: If you have an object which implements Runnable then you start a thread to run that object like this:
    Runnable r = // some object which implements Runnable
    new Thread(r).start();Not what you wanted? Go ahead and clarify then.

  • Panel implements Runnable?

    Is it possible to implement Runnable in a Frame panel?
    I have an Applet Frame for drawing polylines and I want to add a scrolling text panel at the bottom of the frame.
    I have a horizontal text applet already, however, when I try to add it's functionality to the frame's panel I get a nullpointerexception error.
    Can anybody help,
    thanks Aidan

    This is the original applet that I used for scrolling text.
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TextPanel extends Applet implements Runnable
    private Thread textthread;
    boolean FirstPass;
    private String Text;
    private int S;
    private Color bgC;
    private Color textC;
    private Color tempC;     
    private int xPos;
    private int yPos;
    private int textWidth;
    private int aWide;
    private int aHigh;
    private String fontName;
    private Font F;
    private Image iBuff;
    private Graphics gBuff;
    private Image iTheText;
    private Graphics gTheText;
    private boolean LoadPause;
    private int RP;
    private int VB;
    public TextPanel()
    textthread= null;
    FirstPass = true;
    Text = " Scrolling Text. ";          
    S = 40;
    xPos = 1;
    yPos = 0;
    textWidth = 0;
    aWide = 0;
    aHigh = 0;
    bgC = new Color(255, 255, 255);          
    textC = new Color(0, 0, 0);
    tempC = textC;               
    fontName = "TimesRoman";
    LoadPause = true;
    RP = 1000;
    VB = 0;
    iBuff = null;
    gBuff = null;
    public void init()
    aWide = 600;
    aHigh = 16;
    prepMessage();
    makeText();
    if (iBuff == null)
    iBuff = createImage(aWide, aHigh);
    gBuff = iBuff.getGraphics();
    public void prepMessage()
    FontMetrics fontmetrics = null;
    F = new Font(fontName, Font.PLAIN, 16);
    fontmetrics = getFontMetrics(F);
    textWidth = fontmetrics.stringWidth(Text);
    int j = fontmetrics.getAscent();
    yPos = aHigh - fontmetrics.getMaxDescent() - fontmetrics.getMaxDescent() / 3;
    yPos = yPos + VB;
    public void makeText()
    iTheText = createImage(textWidth, aHigh);
    gTheText = iTheText.getGraphics();
    gTheText.setColor(bgC);          
    gTheText.fillRect(0, 0, textWidth, aHigh);
    gTheText.setColor(tempC);          
    gTheText.setFont(F);
    if(!FirstPass)
    gTheText.drawString(Text, 0, yPos);
    public void update(Graphics g)
    paint(g);
    public void paint(Graphics g)
    if(++xPos > textWidth)
    xPos = 1;
    int i = xPos * -1;
    do
    if(!FirstPass)
    gBuff.drawImage(iTheText, i, 0, this);
    if(FirstPass)
    gBuff.drawImage(iTheText, 0, 0, this);
    i = 0;
    i += textWidth;
    } while(i < aWide);
    g.drawImage(iBuff, 0, 0, this);
    public void start()
    if(textthread== null)
    textthread= new Thread(this);
    textthread.start();
    public void stop()
    if(textthread!= null)
    textthread= null;
    public void run()
    if(FirstPass)
    FirstPass = false;
         makeText();
         if (!FirstPass)
         do
    try
    repaint();
    if(LoadPause)
    try
    TextPanel _tmp = this;
    Thread.sleep(RP);
    catch(InterruptedException interruptedexception) { }
    LoadPause = false;
    TextPanel _tmp1 = this;
    Thread.sleep(S);
    catch(InterruptedException interruptedexception1)
    stop();
         }while(true);
         else
         return;
    I was hoping to have a class
    Where the applet created a frame with e.g. a canvas panel and a textscrolling panel i.e. by changing the init() method to include the following.
    public void init()
    Frame frame = new Frame("Text scroller");
    frame.setSize(600, 100);
    Panel panel = new Panel();
    panel.setSize(aWide, aHigh);
    TextPanel textpanel = new TextPanel();
    panel.add(textpanel);
    frame.add(panel);
    textpanel.start();
    frame.setVisible(true);
    The text scroller runs in the html page and the frame is empty. is it possible to add the scrolling text to the frame.

  • Access denied when I implement Runnable?

    Wow.. I've been trying to isolate this problem for ages. I just got down to it by first making an applet that displays a static image, which works fine, and then using a run() method to animate it with just one more frame. When I use the run method it churns out a lot of rubbish in the DOS window, which ends
    at sun.applet.AppletPanel.run(AppletPanel.java:293)
    at java.lang.Thread.run(Thread.java:484)
    I don't know what's going on here... Is there a problem with my JDK, because I've installed it twice already? It compiles fine, with just one mention that I've overridden a method, namely paint, which is empty anyway. Help!

    Without the code and the exact exception, I can't be entirely sure of the problem, however I can guess. If you are implementing Runnable, you should not be calling your run method directly. You mentioned that this is an applet, so you should write your start method as:
    public void start(){
      (new Thread( this ) ).start();
    }Which will create and start a new thread whose run method (the code it will be executing) is what you have written in your run method.

  • Implements Runnable vs extends Thread

    Hello,
    Why do we call method run() in a Runnable class a thread? (at least my textbook implies such concept)
    If thread is an independent process, which runs on its own - then it's not about Runnable.run().
    public class RunnableThread implements Runnable
        public void run()
            for (int i=0; i<100000; i++)
                if (i%50000 == 0)
                System.out.print(i+" ");
        public static void main (String args[])
            System.out.println("Before thread");
            new RunnableThread().run();
            System.out.println("Thread started");// this line is executed only after
            // run() returns, not like with "true" threads, where execution course          
            //doesn't wait for start() to return
    }Or should I consider run() a regular (non-thread) method needed only to bypass extends restrictions?

    Why do we call method run() in a Runnable class a
    thread? We don't.
    (at least my textbook implies such concept)Perhaps you could post what your textbook says, and we can decipher it for you.
    If thread is an independent process, which runs
    on its own - then it's not about Runnable.run().Don't know what you mean by it being "about" Runnable.run()?
    Runnable.run is the method that gets executed when a thread is started.
    Or should I consider run() a regular (non-thread)
    method needed run() is a regular method. It happens to be one that is declared in the Runnable interface and is called by an executing thread. In your example code, you use just call run as you would any other method, so it acts just like any other method. To run it in a separate thread, you should call start() on the thread, not run(). The Thread object will then enter the waiting state and will call run() itself at the appropriate time.

  • Performance wise which is best extends Thread Class or implement Runnable

    Hi,
    Which one is best performance wise extends Thread Class or implement Runnable interface ?
    Which are the major difference between them and which one is best in which case.

    Which one is best performance wise extends Thread Class or implement Runnable interface ?Which kind of performance? Do you worry about thread creation time, or about execution time?
    If the latter, then don't : there is no effect on the code being executed.
    If the former (thread creation), then browse the API Javadoc about Executor and ExecutorService , and the other execution-related classes in the same package, to know about the usage of the various threading/execution models.
    If you worry about, more generally, throughput (which would be a better concern), then it is not impacted by whether you have implemented your code in a Runnable implementation class, or a Thread subclass.
    Which are the major difference between them and which one is best in which case.Runnable is almost always better design-wise :
    - it will eventually be executed in a thread, but it leaves you the flexibility to choose which thread (the current one, another thread, another from a pool,...). In particular you should read about Executor and ExecutorService as mentioned above. In particular, if you happen to actually have a performance problem, you can change the thread creation code with little impact on the code being executed in the threads.
    - it is an interface, and leaves you free to extend another class. Especially useful for the Command pattern.
    Edited by: jduprez on May 16, 2011 2:08 PM

  • Naming a thread that is created implementing Runnable

    How could I name a thread that I create using Runnable Interface?
    public class Test {
         * @param args the command line arguments
        public static void main(String[] args) {
            TestRunnable tr = new TestRunnable();
            /* running thread */
            new Thread(tr).start();//THREAD 3
    public class TestRunnable implements Runnable {
        public void run() {
            for(int y = 1; y < 1000; y++) {
                System.out.println("3333333333333333333333333333333333333333 " + Thread.currentThread() );
    }

    well, I'm just experimenting; learning about Threads. As you can see I
    was able to name the other two threads, I was just curious how you would do it,
    using the Runnable Interface, seeing as those two naming options I used don't
    seem to be an option for it. I may be misunderstanding your reply...
        public static void main(String[] args) {//thread 0
            FrameThread ft = new FrameThread();//extends Thread
            ft.setName("ft");
            Thread td = new Thread("td") {
                @Override
                public void run() {
                    for(int a = 1; a < 1000; a++) {
                        System.out.println("1111111111111111111111111111111111111111 " + Thread.currentThread() );
            TestRunnable tr = new TestRunnable();//class implements Runnable
            /* running threads */
            td.start();//THREAD 1
            ft.start();//THREAD 2
            new Thread(tr).start();//THREAD 3
    }I'm naming them so when I use : Thread.currentThread() the return slot has the name I provide.
    Edited by: rico16135 on May 3, 2008 3:14 PM
    Edited by: rico16135 on May 3, 2008 3:17 PM

  • Extending Applet implements Runnable    --explain

    kindly give an explanation of the need to use the
    <extends Applet implements Runnable > code
    while creating an applet program is there a need to use both Applets and Runnable
    wht are the methods available in Applet class
    and Runnable interface

    The most common use of the Runnable interface is for threading.
    An applet doesn't need to implement Runnable to be run as an Applet, but an applet often needs to be doing things in the background, not just when specific user events like init, start, mouse events etc. come in. For example the applet might run some kind of animation.
    An applet should return promptly from events of the above sort, allowing the browser to get on with it's own business. If it is to do something itself one of these events needs to start a thread.
    Declaring the Applet runnable allows you to do something like:
    new Thread(this).start();for example in the init method. This starts a new thread of execution which runs the run method of the applet, which will do the background activity.
    You don't have to do it this way, you can create another Runnable object whose run method will be executed by the thread. Often you use anonymous classes for this e.g.
    new Thread(new Runnable() {
       public void run() {
              doBackgroudStuff();
        }).start();

  • What are the different options for implementing web security?

    Hi,
    Right now I am working on an internet website. We are using JSP for presentation and running Weblogic Application Server. I want to know different options for implementing website security. One of the options that I am aware of is to use LDAP. But we donot want to go and buy a LDAP Directory Server now. So I would really appreciate if somebody could let me know my choices here.
    Thanks in advance.

    Hi,
    If you are working on a Windows 2000 platform, the most obvious choice would be Active Directory Server as this is shipped free with Server 2000. It is LDAP compliant, although does have a few differences that set it apart from the other X500 standard based solutions which I will mention in a moment. Details on these differences can be found at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnactdir/html/msdn_activedirvsnds.asp
    Other options are openldap, an open source implementation of an ldap server or iPlanet's Directory Server. If you are initially doing an evaluation, a trial version is available of the iPlanet software and can be downloaded from their site. I found this particularly easy to get to grips with and their is excellent documentation available. There is also an offering from Novell, but I have no experience of this.
    Hope this helps.
    Jon

  • Best practice for implementing Manufacturing Cost Planning ( MCP)

    is there any best practice for implementing Manufacturing Cost Planning ( MCP) using BI-IP?

    Hi:
            Both options are viable. If you reverse posting in FB50 then FI GL account postings will also be reversed and along with cost center postings. Hence here advantage is that cost center reversal will be with referenced to the original document with which wrong posting were made. Disadvantage here is that you will to post the entry again in FB50 . In KB11N you will simply transfer cost center amount from wrong to new one that should be in place of it but here you will have no reference . I personally think reversing posting through FB50 is viable options , reverse postings can be seen in KSB1 as well against that cost center.
    Regards

  • What are the pre requisites for implementing ChaRM

    Hi
    We are planning to implement ChaRM & CTS+ in our organization. We are using three system landscape and we have EP, PI, BI and ECC systems.
    Can you please tell me what are the pre requisites for implementing ChaRM & CTS+ and what are the areas i need to look before starting the configuration
    Thanks & Regards
    Anand

    The listed pre-requisites for the implementation of ChaRM are;
    1.  Already completed the basic configuraiton of SAP Solution Manager
    2.  You have set-up your solution, landscape and installed base (iBase) for the systems to be integrated
    3.  you have setup business partners for the users (or at least 1)
    4.  satellite systems are at the minimum  support package level required (note 907768)
    5.  connections are available to the satelite systems
    6.  CTS+ if you wish to control non ABAP change requests through ChaRM

  • Best Practices for Implementing BI7.0

    Dear all,
    We are currently in BI 3.5 and have planned to go for BI 7.0.I have a few questions
    1. Is the BI in Netweaver 2004s is BI7.0?
    2. What are the best practices to go for BI 7.0? I found few documents regarding the Best Practices in service.sap.com
    3. Where can I find more detailed information and documents for implementing BI7.0?
    If you have any document can you please send it to
    (yo - no email addresses in here buddy boy)
    Thanks & Regards,
    Chandran Gansan
    Message was edited by: Ron Silberstein

    Dear Chandran,
      1. Is the BI in Netweaver 2004s is BI7.0?
    >> I read some posts before that the correct term should be SAP Netweaver 2004s; Whereas the SAP BW3.5 is referred to SAP Netweaver 2004. I hope I am not mistaken.
      2. What are the best practices to go for BI 7.0? I found few documents regarding the Best Practices in service.sap.com
      3. Where can I find more detailed information and documents for implementing BI7.0?
    >> Since you have access to the SAP service marketplace, kindly check under the categories: bi, bifaq, sevices & implementation.
      Hope this helps..
      Thanks...

  • Is licence required for implementing JavaTv and JMF.

    Hi,,
    I am trying to develop GEM middleware for my STB,
    The STB has OS20 as RTOS and implemented on an ST chip
    This GEM is DVB MHP minus DVB.
    We have to implement JavaTV package and JMF for that,
    But do we have to pay any royalty to SUN for implementing the JavaTV or JMF packages or can we implement the binary versions of the packages.
    Please letme know how to implement the following packages
    org.havic.*
    org.davic.*
    javax.tv.*
    org.dvb.*
    and JMF?

    Hi Rohit,
    let me also add a few words. In principle the process Sales Order Processing B2B with ERP sales order in CRM Web Channel means that you setup (a) Web shop(s) that use and display the CRM product catalog but create orders directly in SAP ERP without first creating them in SAP CRM. It also allows to use certain E-Marketing features of CRM in the Web shop. The CRM product catalog in this process can only be used if you do use the TREX. There is no way of directly call up the catalog from CRM in the Web shop by bypassing the TREX.
    In the SAP E-Commerce for SAP ERP solution (ECO ERP) we in contrast offer the possibility to use the ERP catalog without the TREX. In this solution you can use the Memory Catalog which is not using the TREX. This solution by this way allows to directly use and display the ERP catalog and create orders directly in SAP ERP.
    For the CRM catalog in contrast we do not have something similar to the Memory Catalog. Instead you DO need to use the TREX to display the CRM catalog in the Web shop.
    The only option you have to "avoid" the TREX i a CRM web shop is what Easwar and Christoph have written about: The usage of an external catalog from a 3rd party catalog engine via the Open Catalog Interface (OCI) in the CRM Web shop. This we do offer for the CRM Web shop. However if you do not have an external catalog engine and want to use the CRM catalog then again you do need to use the TREX. It does not matter if you do not want to use product search nor prices other than fro ERP sales order.
    Greetings
    Torsten Kliesch

Maybe you are looking for