Question about Threads/Servlets

Let's say I have a servlet that opens a socket connection to a server application. On the server end, I would have to make a thread for each connection. But what about the Servlet? do I have to deal with Threads on the servlet side or does the servlet engine takes care of that?

Unless your servlet implements the SingleThreadModel interface, the servlet container shoud take care of running each request to your servlet in a separate thread.
Andy Nguyen

Similar Messages

  • Dumb question about Thread Safety in Servlets

    Hi all
    I wrote this Client API for sending requests and receiving responses to / from a multivalue database. The API is called by my Servlet. Now it seems my API is not thread safe because when several people open up the servlet at the same time, the API gets totally confused. When the API calls are inside a synchronized(){} it works just fine, but obviously at a big performance hit. Is that the wrong way of doing it??
    However when I was doing the ACID test locally on my machine, by opening two command prompts and excuting the same java program (with the same code in it as the servlet, but standalone) my API worked just fine. How come?
    Any insights appreciated as I am just learning about thread safety now (the hard way :-( )
    cheers
    Dejan

    Does this help
    Are you using one connection to the database shared by all instances
    of your servlet
    And is this connection create in the init method of the servlet and stored
    in the servlet context.
    Problem 4 people try and use your servlet at the same time, each servlet trys to
    create a connection to the database and then store it in the servlet context and
    this causes a problem.
    Solution create a listener to create the connection and store it in the servlet context
    when the servlet is created.
    If this is your problem it is not advisable to use only one connection to the db
    try using db pooling

  • Questions about Java Servlets and JSP

    Hi,
    I'm a confident Java Programmer (and really enjoy using this language) but am very new to Java servlets and Java Server Pages.
    I have previously worked with Perl on my web projects (simple 'league' style voting pages). I read in my 'Core Java' book that I should no longer use perl or even cgi.
    I need to know more about Java servlets and Java Server Pages so I can make the switch to a 'real' programming language.
    I have a few questions:
    How should I start to learn JS and JSP?
    How applicable will the java knowlegdge I have already be?
    Are JSP common on the world wide web?
    What tools do I need to start? (I currently develop in JBuilder and have Java 1.4.1 Standard Edition)
    Is it likey my web host (and others) will support JSP?
    Thank-you very much for helping a novice get started,
    Regards,
    Paul

    Hi, Steve ...has to be frustrating! But do not despair.
    Let's suppose the servlet it's named MyServlet on package org.servlets
    WEB-INF should look:
    WEB-INF
    classes
    org
    servlets
    MyServlet.class
    web.xml
    web.xml file should have this two declarations:
    <web-app>
      <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>org.servlets.MyServlet</servlet-class>
      </servlet>
      <!-- other servlets -->
      <servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/MyServlet</url-pattern>
      </servlet-mapping>
      <!-- other servlets mappings -->
    </web-app>Now, once the container starts (Tomcat?), you should be able to see that servlet in:
    http://localhost:8080/[my-context/]MyServletAnd what my-context is? The web application context. This string should be empty if your're deploying to the root context, otherwise should the context name. In Tomcat, deploying to root context defaults to using webapps/ROOT.
    Sorry for my English, but I felt the need to answer your request. I hope it helps despite my writing.

  • Newbie question about loading servlets on tomcat

    I have what is probably a very basic question about loading simple servlets on to tomcat to test its installation. I have followed instructions from numerous tutorials to the letter but still I can't get it to work.
    I have installed tomcat on win2k in c:\tomcat. I set up the jdk, environment vars (JAVA_HOME, CATALINA_HOME, TOMCAT_HOME) which all point at the correct dirs. I can compile a servlet without errors. I can also place a test jsp and html file into the root directory and they both work fine.
    However, now I am trying a test servlet and no matter what I do it gives me a 404. I have a servlet class file called "HelloServlet.class" which I placed into the %install_dir%\webapps\ROOT\WEB-INF\classes directory. I try to reference it using this url:
    http://localhost/servlet/HelloServlet
    Tomcat is configured to use port 80 and has been restarted after adding the servlet class file. Does anyone have a clue why this is not working for me?
    Many thanks
    Marc

    You have to add in the web.xml file that it is in the WEB-INF dir, the information about your servlet. An example:
    <web-app>
    <servlet>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/HelloServlet</url-pattern>
    </servlet-mapping>
    </web-app>

  • Some questions about Java servlets

    I am having some problems with my Java servlets. Here they are below.
    #1 I have a login jsp page. When user logs in, the MySQL database is queried. If a match, redirect to appropriate page. The problem is I can't seem to remain in the login page if there is no match, I get a blank screen. If there is no match, how can I redirect it back to the login screen? For example, my login screen is login.jsp. Here is my code below.
    while(rs.next())
    if(rs != null)
    String name = rs.getString("USERNAME");
    Cookie getUser = new Cookie("User", name);
    response.addCookie(getUser);
    String sql2 = "INSERT INTO answers (USERNAME) VALUES( '" + name +"')";
    ResultSet rs2 = stmt.executeQuery(sql2);
    response.sendRedirect("profile410.jsp");
    out.println("<p>inside if structure");
    #2 After I go to the first screen after login, I am filling out a questionaire, and everytime I click on a submit button a different servlet comes into play, called InsertRecords.java. Everytime I go from one jsp to another, information gets stored into a database, InsertRecords.java is controlling this. I use the below code.
    String delete = request.getParameter("delete");
    String question = request.getParameter("question");
    String value = request.getParameter("R");
    if (delete.equals("no") && !value.equals(""))
    String sql = "INSERT INTO answers (" + question + ") VALUES (" + value + ")";
    int numRows = stmt.executeUpdate(sql);
    out.println("Record has been inserted");
    String nextPage = request.getParameter("nextPage");
    Cookie[] cookies = request.getCookies();
    if (cookies != null)
    for (int i = 0; i < cookies.length; i++)
    String name = cookies.getName();
    String valuecook = cookies.getValue();
    Cookie getUser = new Cookie(name, valuecook);
    response.addCookie(getUser);
    response.sendRedirect(nextPage);
    the table is answer and the fields are ID, username, and q1, q2 q3, up to q11. the idea is upon login, the username gets stored into the answer table, the field username. I want the values stored in the same row everytime user jumps from one page to another based on his username. Goes to first jsp, q1 gets inserted, next jsp, q2 gets inserted, etc. But they all get inserted diagonally on different rows, not the same one, that is the problem. How can I fix this?
    #2 Based on the above code, say there is 11 jsp pages, remember, this is an online questionaire. When user logs in, he starts at the first jsp page, or question. When for example when the browser gets cut off at question6, when he logs back in, I want him to start at question4, if cut of at question 11, start again upon login at question 8. The reason, so he won't have to start from the beginning. Each question is on seperate jsp's. The way I see this happening is creating a session upon login and keeping that session. And grab 4th question when he logs back in, but I am not sure about how to go about it.
    Can someone help me please?

    Q1:
    Use the update command and not insert.
    Q2:
    Won't work. The user may log back in after the session has expired or from a different location. On log in look for a record for that user and what questions have been answered so far.

  • A question about thread safety and the Acrobat SDK

    Hi All,
    On page 12 of this FAQ: http://www.adobe.com/devnet/acrobat/pdfs/Acrobat_SDK_developer_faq.pdf
    It says that Use of any Acrobat product in a multithreaded way is technically impossible.
    I'm currently writing a command line application to perform some basic data gathering on a PDF file. The Application only makes use of a PDDoc object, and never calls on any other kind of object (i.e. AVDoc).
    The application itself is not multithreaded. All of the logic runs in a single thread.
    However, the application will be called (via the command line) from another application that /is/ multithreaded. I think that this might be fine, but I wasn't sure. In this case, would this count as a single thread, but spread across multiple processes? And if that is the case, would that be OK with the SDK?
    Or would having multiple invocations/calls into the Acrobat DLLs cause the same issue as a multi-threaded application?
    Unfortunately, I haven't done a lot of work with threads before. This might be a very silly question.

    The application would be called from a perl script that is used to automate several tasks. The app is a console application, written in C# w/ the Acrobat COM components, and Visual Studio 2005.
    The console application uses the Acrobat SDK to instantiate a PDDoc object, open a PDF, and get information about the document. It then returns results back to the console.
    So, the perl script just calls: "C:\pdfinfo.exe -f=myPdf.pdf" and pipes the result to a log file.
    In this case, it never creates a new instance of the Acrobat application, but it does use the SDK.
    The reason that I was concerned was that the perl script is multi-threaded. I wasn't sure if acrobat was just sensitive to multiple threads inside a single process, or if it was unable to handle multiple processes as well.
    PDL's answer suggests that I should be fine as long as a new process is started each time. This is good to hear.

  • Questions about thread priority...

    Situation 1) setPriority(int adsa)
    public class ThreadPrioDemo1 {
          static class Demo1 implements Runnable{
          public void run(){ //blablabla}
         public static void main(String[] asdf){
              Runnable r = new Demo1();
              Thread myThread = new Thread(r);
              Thread mainT = Thread.currentThread();
              //mainT's priority is 5, so as myThread.
            mainT.setPriority(10);
    //mainT's priority to MAX, this simultaneously changes myThread to 10 as well.
            //or
            myThread.setPriority(10);
    //myThread priority to MAX, however, this does not change mainT to 10
    }Question 1), why if main Thread is set to a certain priority, the thread it creates automatically change its priority to the same as well, but the reverse is different??
    Situation 2) this is slightly more complex
    public class ImplementingRunnable {
         public static void main(String[] args) {
         Thread mainT = Thread.currentThread();
              for(int ii=0 ; ii<args.length ; ii++) {
                   Runnable r = new MyRunnable(args[ii]);
                   Thread t = new Thread(r);
                t.setDaemon(true);
                //t.setPriority(Thread.MAX_PRIORITY);
                   t.start();
    }and
    public class MyRunnable implements Runnable {
        public void test(){
        System.out.println("test");
         String message;
         public MyRunnable(String msg) {
              message = msg;
         public void run() {
              Thread me = Thread.currentThread();
              try {
                   for(int ii=0 ; ii<10 ; ii++) {
                       //case (1) me.setPriority(Thread.MIN_PRIORITY);
                        me.sleep(3);
                        System.out.println(message);
                        //case (2) me.setPriority(Thread.MIN_PRIORITY);
              } catch (InterruptedException ie) {
    }In class ImplementingRunnable, how is the commented code line related or counter-related with the commented case 1 code line in MyRunnable??
    Please help
    thanks

    Let me speak my question again very simply:
    1)
    Say I have two threads, 1 is main() thread, the program entry point, 2 is another thread created by main().
    Now, the default priority for both two is 5. If I change the priority for main() to a certain level, the other thread created by it automatically change its priority to the same level? why? and however, the reverse (in this case, if I change the priority for the thread created by main()) is not.
    2)
    public class Demo{
    static class MyThread implements Runnable{
    public void run(){//some thing}
    Thread t = new Thread(this);
    t.setPriority(10);
    public static void main(String[] afd){
    Runnable r = new MyThread();
    Thread t1 = new Thread(r);
    t1.setPriority(1);
    }What can you say about both bold code lines?
    If I use println() to track the Priority, the final priority, that is, t1, is 1. It is logical, however, the program behaves differently without the bold code line in the static class MyThread, despite the final priority for t1, is the same, 1.
    Any help by now??
    thanks alot

  • I'm a newbie: I have a question about threads

    midp 2.0
    Java SE 5.0
    J2ME version 2.2
    Below is my code I'm stucked with..... The code here shows a midlet class
    and another class derived from Thread (NetworkThread). This NetworkThread
    gets started from the main midlet... Search my code for the term ??????? and
    there you find my trouble area... What I'm having trouble with is that at
    that point in my code a NetworkThread has been given a url to access, and
    putting network access in the main thread is a bad thing because one can
    never know how long it takes to access the server... I want this line:
    System.out.println("NETWORK COMMINUCATION DONE"); to be processed after
    NetworkThread is done requesting the url.... I'm not sure how to solve this
    code so that the midlet waits for NetworkThread to access the url... But
    while NetworkThread access the url I want the midlet to response to user
    input, I don't want it to look like the midlet has crashed......
    Any tips on how I can solve this issue will be greatly appreciated...
    By the way, if you see anything else that could have been improved in my
    code, then please tell me about it too....
    MY CODE:
    NETWORKTHREAD:
    package com.test;
    import java.io.IOException;
    import java.io.*;
    import java.util.*;
    import javax.microedition.io.*;
    public class NetworkThread extends Thread
    private boolean networkStop;
    private boolean networkPause;
    private HttpConnection httpConnection = null;
    private InputStream inputStream;
    private String Url;
    private String netCommand = null;
    private String netArg = null;
    private LoginForm loginForm;
    public NetworkThread(String serverURL)
      Url = serverURL;
    synchronized void requestStop()
      networkStop = true;
      notify();
    synchronized void resumeGame()
      networkPause = false;
      notify();
    synchronized void setCommand(String cmd, String arg)
      System.out.println("setCommand = " + cmd);
      netCommand = cmd;
      netArg = arg;
      networkPause = false;
      notify();
    void pauseThread()
      networkPause = true;
    public void run()
      networkPause = true;
      networkStop = false;
      while (true)
       if (networkStop) {
        break;
       synchronized(this) {
        while (networkPause) {
         try {
          wait();
         catch (Exception e) {}
       synchronized(this) {
         if (netCommand != null) {
           if (netCommand.equals("LOGIN")) {
             //Here some networking processing will
             //be done
         else if (netCommand.equals("LOGOUT")) {
         netCommand = null;
       pauseThread();
    THE MIDLET:
    package com.test;
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.io.*;
    import java.io.IOException;
    import java.lang.String;
    public class Test extends MIDlet
      private Display display;
      private NetworkThread networkThread;
      private String Url;
      public Test() {
        display = Display.getDisplay(this);
      public void startApp() throws MIDletStateChangeException {
        if (networkThread == null) {
          networkThread = new NetworkThread(Url);
          networkThread.start();
      else {
         networkThread.start();
    public void destroyApp(boolean unconditional) throws
    MIDletStateChangeException {
       public void pauseApp() {
       public void commandAction(Command c, Displayable s) {
         if (c == okCommand) {
           networkThread.setCommand("LOGIN", "arg1");
           System.out.println("NETWORK COMMINUCATION DONE");
    }

    You will probably need to learn about HTTP and XML to complete this project. If you don't know Java at all then I would suggest starting with tutorials like these ones first
    http://java.sun.com/docs/books/tutorial/index.html
    Have a happy day.

  • Urgent question about Thread-safety

    Hi all,
    the new tiger release provides an "isReachable()" method for the "InetAddress" object.
    I've found, this method is not thread-safe (see the source and output below).
    It returns true for all threads, when multiple threads using this method with different adresses are running at a time and one of the addresses is reachable. This happens only on WinXp. Running on Linux, the output is like expected.
    I've tried to report this as a bug. But the gurus answered, taking care of thread safety would be a "programmers task".
    My question is, what can I do, to be thread-safe in my case?
    W.U.
    import java.util.*;
    import java.net.*;
    public class IsReachableTest_1 extends Thread{
        static volatile int inst=1;
        static final String NET_ADDR="192.168.111.";
        int instance=inst++;
        public void run(){
            for(int i=19;i<23;i++){
                try{
                    long start=System.nanoTime();
                    if(InetAddress.getByName(NET_ADDR+i).isReachable(1000))
                        System.out.println(""+instance+"--host found at:"+NET_ADDR+i+"--time:"+(System.nanoTime()-start)/1000000);
                    else
                        System.out.println(""+instance+"--no host at:"+NET_ADDR+i);
                }catch(Exception e){System.out.println(""+instance+"--ERROR "+e.toString());}
            System.out.println(""+instance+"--done.");
        public static void main(String[] args) {
            System.out.println(
                System.getProperty("java.vendor")+" "+
                System.getProperty("java.version")+" running on "+
                System.getProperty("os.name")+" "+
                System.getProperty("os.version"));
            Vector v=new Vector();
            System.out.println("\nTest 1: One after another:");
            for(int i=0;i<10;i++){
                IsReachableTest_1 t;
                t=new IsReachableTest_1();
                t.start();
                try{
                    t.join();
                }catch(Exception e){System.out.println("MAIN1: "+e.toString());}
            System.out.println("\nTest 2: All together:");
            inst=1;
            for(int i=0;i<10;i++){
                IsReachableTest_1 t;
                t=new IsReachableTest_1();
                t.start();
                v.addElement(t);
            for(Iterator i=v.iterator();i.hasNext();)
                try{
                    ((IsReachableTest_1)i.next()).join();
                }catch(Exception e){System.out.println("MAIN2: "+e.toString());}
                System.out.println("\nALL DONE");
    And here is the output, when running on WinXp:
    Sun Microsystems Inc. 1.5.0-beta running on Windows XP 5.1
    Test 1: One after another:
    1--no host at:192.168.111.19
    1--no host at:192.168.111.20
    1--host found at:192.168.111.21--time:2
    1--no host at:192.168.111.22
    1--done.
    2--no host at:192.168.111.19
    2--no host at:192.168.111.20
    2--host found at:192.168.111.21--time:4
    2--no host at:192.168.111.22
    2--done.
    3--no host at:192.168.111.19
    3--no host at:192.168.111.20
    3--host found at:192.168.111.21--time:1
    3--no host at:192.168.111.22
    3--done.
    4--no host at:192.168.111.19
    4--no host at:192.168.111.20
    4--host found at:192.168.111.21--time:1
    4--no host at:192.168.111.22
    4--done.
    5--no host at:192.168.111.19
    5--no host at:192.168.111.20
    5--host found at:192.168.111.21--time:3
    5--no host at:192.168.111.22
    5--done.
    6--no host at:192.168.111.19
    6--no host at:192.168.111.20
    6--host found at:192.168.111.21--time:1
    6--no host at:192.168.111.22
    6--done.
    7--no host at:192.168.111.19
    7--no host at:192.168.111.20
    7--host found at:192.168.111.21--time:1
    7--no host at:192.168.111.22
    7--done.
    8--no host at:192.168.111.19
    8--no host at:192.168.111.20
    8--host found at:192.168.111.21--time:1
    8--no host at:192.168.111.22
    8--done.
    9--no host at:192.168.111.19
    9--no host at:192.168.111.20
    9--host found at:192.168.111.21--time:1
    9--no host at:192.168.111.22
    9--done.
    10--no host at:192.168.111.19
    10--no host at:192.168.111.20
    10--host found at:192.168.111.21--time:1
    10--no host at:192.168.111.22
    10--done.
    Test 2: All together:
    1--no host at:192.168.111.19
    2--no host at:192.168.111.19
    3--no host at:192.168.111.19
    4--no host at:192.168.111.19
    5--no host at:192.168.111.19
    6--no host at:192.168.111.19
    7--no host at:192.168.111.19
    8--no host at:192.168.111.19
    9--no host at:192.168.111.19
    10--no host at:192.168.111.19
    2--no host at:192.168.111.20
    3--no host at:192.168.111.20
    6--host found at:192.168.111.20--time:924 <----- this host does not exist!!
    5--host found at:192.168.111.20--time:961 <----- this host does not exist!!
    10--host found at:192.168.111.20--time:778 <----- this host does not exist!!
    9--host found at:192.168.111.20--time:815 <----- this host does not exist!!
    2--host found at:192.168.111.21--time:37
    7--host found at:192.168.111.20--time:888 <----- this host does not exist!!
    8--host found at:192.168.111.20--time:852 <----- this host does not exist!!
    4--host found at:192.168.111.20--time:997 <----- this host does not exist!!
    1--host found at:192.168.111.20--time:1107 <----- this host does not exist!!
    3--host found at:192.168.111.21--time:38
    6--host found at:192.168.111.21--time:1
    5--host found at:192.168.111.21--time:1
    10--host found at:192.168.111.21--time:2
    2--host found at:192.168.111.22--time:3 <----- this host does not exist!!
    9--host found at:192.168.111.21--time:2
    7--host found at:192.168.111.21--time:1
    4--host found at:192.168.111.21--time:3
    1--host found at:192.168.111.21--time:39
    2--done.
    1--host found at:192.168.111.22--time:5 <----- this host does not exist!!
    1--done.
    10--host found at:192.168.111.22--time:40 <----- this host does not exist!!
    3--host found at:192.168.111.22--time:192 <----- this host does not exist!!
    6--host found at:192.168.111.22--time:75 <----- this host does not exist!!
    8--host found at:192.168.111.21--time:230
    5--host found at:192.168.111.22--time:155 <----- this host does not exist!!
    4--host found at:192.168.111.22--time:78 <----- this host does not exist!!
    9--host found at:192.168.111.22--time:77 <----- this host does not exist!!
    7--host found at:192.168.111.22--time:76 <----- this host does not exist!!
    10--done.
    6--done.
    4--done.
    5--done.
    3--done.
    7--done.
    9--done.
    8--no host at:192.168.111.22
    8--done.
    ALL DONE

    I created this test (it's basically the same as your class):
    import java.util.*;
    import java.net.*;
    public class IsReachableTest_2 implements Runnable {
        private final String[] addresses = new String[] {
             "www.sun.com",
             "129.42.16.99" // www.ibm.com which is not reachable
        public void run(){
            try {
                for (int i = 0; i < addresses.length; i++) {
                    final long start = System.nanoTime();
                    final String address = addresses;
         if (InetAddress.getByName(address).isReachable(5000)) {
         System.out.println(Thread.currentThread().getName() + ": Host found at: " + address +
              " --time: " + (System.nanoTime() - start) / 1000);
         } else System.out.println("no host at: " + address);
    } catch(Exception e){
    e.printStackTrace();
    System.out.println("Thread " + Thread.currentThread().getName() + " DONE");
    public static void main(String[] args) {
    System.out.println(
         System.getProperty("java.vendor") +
         " " +
         System.getProperty("java.version") +
         " running on " +
         System.getProperty("os.name") +
         " " +
         System.getProperty("os.version")
    for (int i = 0; i < 10; i++) {
         final Thread t = new Thread(new IsReachableTest_2(), "THREAD " + (i+1));
         t.start();
    And I get:
    Sun Microsystems Inc. 1.5.0-beta running on Windows 2000 5.0
    THREAD 1: Host found at: www.sun.com --time: 217653
    THREAD 3: Host found at: www.sun.com --time: 214404
    THREAD 6: Host found at: www.sun.com --time: 214900
    THREAD 4: Host found at: www.sun.com --time: 215901
    THREAD 5: Host found at: www.sun.com --time: 216666
    THREAD 10: Host found at: www.sun.com --time: 216620
    THREAD 9: Host found at: www.sun.com --time: 217405
    THREAD 2: Host found at: www.sun.com --time: 220705
    THREAD 7: Host found at: www.sun.com --time: 220845
    THREAD 8: Host found at: www.sun.com --time: 221384
    no host at: 129.42.16.99
    Thread THREAD 4 DONE
    no host at: 129.42.16.99
    Thread THREAD 6 DONE
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    Thread THREAD 5 DONE
    Thread THREAD 10 DONE
    Thread THREAD 9 DONE
    Thread THREAD 7 DONE
    Thread THREAD 3 DONE
    Thread THREAD 1 DONE
    Thread THREAD 2 DONE
    Thread THREAD 8 DONE
    HOWEVER: I was getting some strange results every so often. Results like:
    Sun Microsystems Inc. 1.5.0-beta running on Windows 2000 5.0
    THREAD 3: Host found at: www.sun.com --time: 261132
    THREAD 9: Host found at: www.sun.com --time: 264183
    THREAD 2: Host found at: www.sun.com --time: 266447
    THREAD 6: Host found at: www.sun.com --time: 266596
    THREAD 8: Host found at: www.sun.com --time: 267192
    THREAD 5: Host found at: www.sun.com --time: 268610
    THREAD 4: Host found at: www.sun.com --time: 269849
    THREAD 1: Host found at: www.sun.com --time: 280978
    THREAD 7: Host found at: www.sun.com --time: 272589
    THREAD 10: Host found at: www.sun.com --time: 273162
    THREAD 3: Host found at: 129.42.16.99 --time: 13657
    Thread THREAD 3 DONE
    THREAD 4: Host found at: 129.42.16.99 --time: 4123
    THREAD 2: Host found at: 129.42.16.99 --time: 9439
    THREAD 5: Host found at: 129.42.16.99 --time: 6681
    THREAD 8: Host found at: 129.42.16.99 --time: 7655
    THREAD 6: Host found at: 129.42.16.99 --time: 8627
    THREAD 9: Host found at: 129.42.16.99 --time: 10586
    Thread THREAD 4 DONE
    Thread THREAD 2 DONE
    Thread THREAD 5 DONE
    Thread THREAD 8 DONE
    Thread THREAD 6 DONE
    Thread THREAD 9 DONE
    no host at: 129.42.16.99
    Thread THREAD 7 DONE
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    Thread THREAD 10 DONE
    Thread THREAD 1 DONE
    Usually the first run after I had compiled the class (!?) This isn't a thread safety problem.

  • A question about threads

    Hi to everybody,
    I'm learning Java and I would like to know what's the difference between extending the Thread class and implementing the Runnable interface.
    Why when I run two objects that are instances of a Runnable class they seem to
    run concurrently, while when I run two objects whose class extends Thread, the virtual machine first executes the first thread , and only when the first thread has died it executes the second (the two threads have the same priority).
    I would also apreciate some clarifying information about "time-slicing" and the use of the method Thread.yield();
    thanks

    Main factor what desides whether to extend Thread or
    Implement Runnable is do you want to extend another.Sorry to say this but: WRONG!
    The main factor in a decision like this should be your model, i.e. is the class you are modelling really a sub-class of Thread, or - more likely - is it a task that should be able to run (on a thread or otherwise)?
    If you are in fact implementing a new kind of Thread (i.e. YourClass is-a Thread), then you extend Thread, otherwise you should implement Runnable.
    Ex:- If your class need to Extend another class then
    you cant extend Thread so you have to use Runnable.This is true, of course, but it should be done for the right reasons.
    So: implement Runnable (unless you are implementing a new kind of Thread)

  • A question about thread programming ...

    Is it possible to modify the following program such that the output is
    ABCABCABC ...
    I tried yield, but not getting results on every run.
    The program is:
    public class Example1 {
    public static void main(String[] args) {
    MyThread t1 = new MyThread("A");
    MyThread t2 = new MyThread("B");
    MyThread t3 = new MyThread("C");
    t1.start();
    t2.start();
    t3.start();
    class MyThread extends Thread {
    private String message = "Hallo!";
    public MyThread() {}
    public MyThread(String s) {message = s;}
    public void run() {
    for (int i = 1; i <= 5; i++) {
    System.out.print(message);
    }

    Not really, no. It's possible (not using yield) to force threads to run in a particular order, but it's kind of missing the point of using threads in the first place!
    Yield is there purely to allow other threads the opportunity to run. It makes no guarantee about which thread will run next.
    If you really must, you need to use a wait() call to force the thread to block, notifyAll calls to resurrect them, and some commonly accessed resource that allows each thread in turn to determine IF it is its turn to run when it is awakened by the notifyAll call. That seems to be the closest to the spirit of what you're trying to do.
    It's a lot of work for something that you can more simply achieve by having only one thread of execution in the first place!

  • A question about thread

    i am learning up on threads.
    A Java program can have many threads, and these threads can run concurrently, either asynchronously or synchronously.
    so lets say i have 2 classes, A and HelloThread
    A
    public class A {
         public static void main(String[] args) throws IOException {
            //(lots of codes)
    }HelloThread
    public class HelloThread extends Thread {
        public void run() {
            System.out.println("Hello from a thread!");
        public static void main(String args[]) {
            (new HelloThread()).start();
    }this is what i am confused.
    both classes have public static void main(), is that possible?
    if no, then what command makes the thread run concurrently?
    (since it says many threads can run concurrently)
    i m soo confused.
    tq

    When you run a Java program the java command gives the name of the main class. The interpretter looks in the class you name for a main() method. There's nothing special about the method, appart from it being used this way. It doesn't matter if there are identical methods in other classes because you tell the interpretter which one to look in.
    By the way, it's not good practice to subclass Thread this way. To run code in a Thread, create a class (or, very often and anoymous class object) which implements Runnable and use the Runnable object in the constructor of Thread.

  • A question about thread!(help a chinese learner)

    package thead;
    import javax.swing.UIManager;
    import java.awt.*;
    class mythread implements Runnable {
    int i;
    String name;
    mythread(String nn){
    i=0;
    name=nn;
    public void run(){
    System.out.println("name"+"starting!");
    try{
    do{
    Thread.sleep(1000);
    System.out.println("IN"+name+"the count is"+i);
    i++;
    while(i<10);
    catch(InterruptedException wwwww){
    System.out.println("interrupt");
    class use {
    public static void main(String[] args) {
    System.out.println("starting");
    mythread pp=new mythread ("ok");
    Thread ww=new Thread(pp);
    ww.start();
    do{
    System.out.print(".");
    try{
    Thread.sleep(100);
    catch(InterruptedException wwwww){
    System.out.println("interrupt");
    while(pp.i!=10);
    System.out.println("ending");
    Why the result is :
    starting
    .okstarting!
    .......INokthe count is0
    ....INokthe count is1
    ..........INokthe count is2
    ...........INokthe count is3
    ........INokthe count is4
    ....INokthe count is5
    ....INokthe count is6
    ............INokthe count is7
    ...........INokthe count is8
    ..........INokthe count is9
    ending
    i can not really understood
    is this about my machine?

    Hmm i was trying your code on my machine and the output was:
    starting
    .namestarting!
    .........INokthe count is0
    ..........INokthe count is1
    ..........INokthe count is2
    ..........INokthe count is3
    ..........INokthe count is4
    ..........INokthe count is5
    ..........INokthe count is6
    ..........INokthe count is7
    ..........INokthe count is8
    ..........INokthe count is9
    ending
    so i guess something's wrong with your vm/os/machine.

  • Question about Threads

    Hi,
    imagine that I have a class as below:
    public class MyVector
    private IntegerVector vect;
    public Synchronized void write(){
    vect.f();
    public Synchronized void read(){
    vect.g();
    Where f and g are non Synchronized and non-static public methods of IntegerVector .
    Imagine that two threads as below:
    thread one :
    class ThreadOne extends Thread
    public ThreadOne(MyVector v)
    this.v=v;
    public void run()
    v.write();
    class ThreadTwo extends Thread
    public ThreadTwo(MyVector v)
    this.v=v;
    public void run()
    v.read();
    My question is that if there will be any conflict between thread1 and thread2 for having the lock on
    object MyVector v ?the methods read and write are Synchronized but they call non-Synchronized methods f() and g()
    of field "IntegerVector vect" of "MyVector v "!
    Thanks,
    Behnaz

    bandarurm wrote:
    jverd wrote:
    bandarurm wrote:
    @OP - Also, remember that there are only two types of locks (aka monitors), which are Object level lock and Class level lock. No. All locks are identical.Could you explain this further? As I thought there is a class level lock (java.lang.Class) for a class with static synchronized methods. And, there is an object level lock, which is a built-in lock that every object has in java, by default.Whenever you synchronize a block of code or a method, you're just obtaining some object's lock. Synchronized methods are just shorthand for obtaining particular objects' locks.
    Synchronization is always the same. Declaring a method synchronized is just shorthand for what you could do by explicitly syncing a block of code on a particular object.
    class Foo {
      synchronized void bar() {
        // body
      // is the same as
      void bar() {
        synchronized (this) {
          // body
      // and
      static synchronized qux() {
        // body
      // is the same as
      static qux() {
        synchronized (Foo.class) {
          // body
    }In all cases, you're just syncing on an object, and which object doesn't matter, except to other methods or blocks that sync on the same object. Everything else is identical.
    The fact that synchronized static methods obtain one particular lock and non-static ones obtain a different one is not indicative of different kinds of locks. It's always just some object's lock, and no lock behaves differently from any other.
    Edited by: jverd on Apr 20, 2009 10:46 AM

  • Challanging question about Threads.  Can anyone help?

    Hello,
    I've been learing how to use threads and I have run into a little rut. I am making a game that listens for clicks of the mouse on the board AND allows people to talk to each other in a chat box.
    I've made a chatThread and in the public void run() method I can do the following...
    public void run(){
    while(true){
    try{
    chatText.append(ServerIn.readLine()+"\n");
    catch (Exception h){}
    this pastes whatever the other person wrote into the public chattext area. now my problem is this. I need another thread that listens for button clicks. If the button is clicked on one side, the other side needs to be able to read that click and perform a certan task. I only have 1 thread running, but I have made an instatance of PrintWriter for the text and DataInputStream for the integer value. I have tried things like this and they really don't like me. (they cause faluts and whatnot)
    public void run(){
    while(true){
    try{
    chatText.append(ServerIn.readLine()+"\n");
    ServerIn2a.readInt();
    catch (Exception h){}
    Sometimes the integer will read into the ServerIn2a and then when i try to chat it can't read into the ServerIn varialble.
    Do I need to make two seperate thread and somehow pause one and run one, then pause the other?
    Thanks for your help!

    Ok, sorry, here is a better description of what my program looks like (the parts that concern this topic)...
    public class Game extends JApplet implements ActionListener, Runnable{
    PrintWriter ClientOut = null; // to send messages to the server
    BufferedReader ClientIn = null; // to receive messages from the server.
    PrintWriter ServerOut = null; // to send messages to the client
    BufferedReader ServerIn = null; // to receive messages from the client.
    DataInputStream ClientIn2a = null; // to send messages to the server
    DataOutputStream ClientOut2a = null; // to receive messages from the server.
    DataInputStream ServerIn2a = null; // to send messages to the client
    DataOutputStream ServerOut2a = null; // to receive messages from the client.
    //On the main screen, if they press the "host" button they become the host and the this happens.....
    //I want these two lines to read text from a dialog box and then pass that text to the other person      //playerinput from a dialog box so it can be passed
    ServerIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    ServerOut = new PrintWriter(clientSocket.getOutputStream(),true);
    //When they click on a button, I am trying to read the buttons coordinate which will be a Integer value. I //I want to get that integer value to the other person so I make these DataInput and Output variables.
    ServerIn2a = new DataInputStream(clientSocket.getInputStream());
    ServerOut2a = new DataOutputStream(clientSocket.getOutputStream());
    //now I made a thread that is always supposed to listen to perform the action of sending the text to
    //the appropriate text listener and to send the integer to the appropriate DATAINPUT listener.
    Thread ServerThread = new Thread(this)
    ServerThread.start();
    //on the main screen, if they press the client button......
    ClientIn = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
    ClientOut = new PrintWriter(serverSocket.getOutputStream(),true);
    ClientIn2a = new DataInputStream(serverSocket.getInputStream());
    ClientOut2a = new DataOutputStream(serverSocket.getOutputStream());
    //now I made a thread that is always supposed to listen and perform the action to send the data to the
    //other person
    Thread clientThread = new Thread(this);
    clientThread.start( );
    //here is the actionPerformed method. They press enter in the text area box and this gets run.....
    if(player==1){
    //THE TEXT THEY TYPE FIRST GETS PASTED INTO THEIR OWN CHAT AREA
         chatText.append(HostUserName+": " + messageField.getText() + "\n");
         //NOW I WANT TO SEND WHEY THEY TYPE TO THE OTHER PERSON
    try{
    ServerOut.write(HostUserName+": " + messageField.getText()+"\n");
    ServerOut.flush(); }
    catch(Exception e){Mbox.showMessageDialog(null,"Chatting error","connect",1);}
    //here is my run method (this is where I think I am having my problems and that I need help with.
    public void run(){
         if(player == server){
         while(true){
         try{
         //THIS IS WHERE THE INTEGER SHOULD BE READ INTO
                   performAFucntion(ServerIn2a.readInt());}
              catch(Exception h){}
              //THIS TRY STATEMENT IS WHERE THE TEXT SHOULD BE READ
         try{   
              chatText.append(ServerIn.readLine()+"\n"); }
         catch (Exception h){}
    //ELSE YOU ARE THE OTHER PERSON AND YOU DO THE EXACT OPPOSITE OF ABOVE
    OK! Now that the code is out of the way. My problem.... Sometimes when I click on a button, the ineger value gets assigned to the ServerIn.reasline and funny symbols pop up in the other persons text area. And then when I try to type text in my text box after I get the wierd symbols into my chat text area, the CATCH (Exceptoin E) from my actionPerformed function that deals with sending the text gets activated and I see the dialog box that tells me there was an error.
    I THINK my error is in my run statement. I think everytime I write something, wether it be an integer or a text, the first .READLINE( ) that gets encountered in my run statement reads it. I think I have to have the WHILE(TRUE) statement or else it wont continuoulsy try to read in data.
    Can anyone tell me if I need to somehow make two threads, one that listens for the text and a seperate one that listens for the integer value?
    I hope this is a little bit more clearer than my last letters. Thanks for being patient with me.

Maybe you are looking for