Home arrow static arrow Java Programming [Archive] - help on programming multi-thread - please
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - help on programming multi-thread - please
This topic has 17 replies on 2 pages.    1 | 2 | Next »

Posts:781
Registered: 5/1/01
help on programming multi-thread - please  
Jul 23, 2004 3:30 PM



 
hi All
i have questions about programming multi-thread.
1. in a servlet, what do i need to code so that the servlet can handle multi-thread requests?
2. how does the program/code decide when a thread is started and ended or two threads are started at the same time?

i am really sure how multiple threads are started and ended. can anyone explain? thanks for you help in advance.
 

Posts:37,103
Registered: 3/30/99
Re: help on programming multi-thread - please  
Jul 23, 2004 4:52 PM (reply 1 of 17)



 
hi All
i have questions about programming multi-thread.
1. in a servlet, what do i need to code so that the
servlet can handle multi-thread requests?

Don't use member variables (other than static finals for constants). The servlet container only instantiates one of your servlet, and will already call service() concurrently. (I think you can tell the container to run in single-threaded mode, but that's probably a bad idea.)

2. how does the program/code decide when a thread is
started and ended or two threads are started at the
same time?

i am really sure how multiple threads are started and
ended. can anyone explain? thanks for you help in
advance.

For example
public class MyRunnable implements Runnable {    public void run() { // this is where a new thread does its work        // do stuff    }} ... void someMethod() {        for (int ix = 0; ix  < 10; ix++) {            Runnable r = new MyRunnable();            Thread th = new Thread(r);            th.start();        }        // Now there are 10 new threads running, each one is doing whatever is in its "do stuff"        // (i.e., its run() method). When a thread's run method completes, that thread is done}


http://java.sun.com/docs/books/tutorial/essential/threads/
 

Posts:781
Registered: 5/1/01
Re: help on programming multi-thread - please  
Jul 23, 2004 5:07 PM (reply 2 of 17)



 
thank you so much for your help.
i read something about not using the stop() to stop a thread. but you said that the thread stops when the run() method exits. can u clarify it more?
and also some application servers such as weblogic, they can handle multi threads, if i need to create a servlet that will be deployed in the server, do i still need to create it to have multi threads, or the server can handle it?
thanks
 

Posts:37,103
Registered: 3/30/99
Re: help on programming multi-thread - please  
Jul 23, 2004 5:19 PM (reply 3 of 17)



 
thank you so much for your help.
i read something about not using the stop() to stop a
thread.

That's right. You don't know what state it's in, so it can lead to trouble. Never call stop(), resume() or whatever other of those methods are deprecated.

http://java.sun.com/j2se/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html

but you said that the thread stops when the
run() method exits. can u clarify it more?

Sure. I didn't mean that the thread's stop() method is called. What happens is (roughly) you call theThread.start(), which causes the VM to create a new thread of execution (not a new Thread object, but a "thread" in the generic sense of a separate stream of instructions). This leads to the run() method being called. You don't know exactly when that thread will get CPU time, or how much, but in chunks or all at once, whatever is in that run() method will be executed. When you reach the end of the run() method, that thread of execution is complete.

and also some application servers such as weblogic,
they can handle multi threads, if i need to create a
servlet that will be deployed in the server, do i
still need to create it to have multi threads, or the
server can handle it?

You don't need to write code that creates and starts threads. You just have to make sure that your servlet is safe for access by multiple threads at once. Basically this means that your service(), doGet(), doPost() methods (others too maybe--don't recall off the top of my head) should not use member variables. Just use method-local variables, and if you need to maintain state between calls, use the session or servlet parameters or something.
 

Posts:781
Registered: 5/1/01
Re: help on programming multi-thread - please  
Jul 23, 2004 6:54 PM (reply 4 of 17)



 
thanks so much, now i am begining to understand the thread more clear. about your last statement.
"
You don't need to write code that creates and starts threads. You just have to make sure that your servlet is safe for access by multiple threads at once. Basically this means that your service(), doGet(), doPost() methods (others too maybe--don't recall off the top of my head) should not use member variables. Just use method-local variables, and if you need to maintain state between calls, use the session or servlet parameters or something.
"
so the servlet doesn't have to extend Thread or implement Runable. just create it the usual way, the server will create the thread as the client requests come in. when do i need to write code to create and start threads in the case of servlet? what about the singlethreadmodel interface. is it wise to implement this interface so that requests are queued? i understand that by doing so, it helps prevent multiple access to datasource. can i just add "sychronized" to the method that accesses datasource?
i am sorry to throw so many questions at you at once. i have read some novel-sized book about thread, but still not clear about it.
by the way, is there a quick way to put > in front of statements?
 

Posts:37,103
Registered: 3/30/99
Re: help on programming multi-thread - please  
Jul 23, 2004 10:10 PM (reply 5 of 17)



 
so the servlet doesn't have to extend Thread or
implement Runable. just create it the usual way,

Correct--extend HttpServlet or whatever.

the
server will create the thread as the client requests
come in.

Um, maybe. It could create a new thread for each request that comes in, but more likely it will create a pool of threads and hand them out to client requests. That's a bit more advanced though, and the main point--that the server (the servlet container) creates the threads--is correct.

when do i need to write code to create and
start threads in the case of servlet?

Probably never. If you wanted to use multiple threads to process one request, your servlet could create its own bunch of threads and dole out its processing to them, but that's not usually what you want to do.

what about the
singlethreadmodel interface. is it wise to implement
this interface so that requests are queued? i
understand that by doing so, it helps prevent multiple
access to datasource. can i just add "sychronized" to
the method that accesses datasource?

I don't know much about the single-threaded model, only that if you use it, your servlet will only process one request at a time. This is usually not a good idea. Unless you have extremely light load or extremely quick processing, you'll get a backlog of requests and pissed off users.

Just throwing in the synchronized keyword someplace that seems like it might make sense without really understanding what's going on is almost guaranteed not to work. Even in simple standalone apps, you have to be careful with how you synchronize, and you have to understand what's going on for it to work. In a servlet you have to be especially careful, as you can end up tying up resources and slowing down request processing.

Read the thread tutorial I linked to above for starters.
 

Posts:37,103
Registered: 3/30/99
Re: help on programming multi-thread - please  
Jul 23, 2004 10:11 PM (reply 6 of 17)



 

by the way, is there a quick way to put > in front of
statements?

Above the the text box where you enter your message, there's a link that says [url http://forum.java.sun.com/post.jsp?forum=31&thread=540818&message=2621570&reply=true&quote=true][quote original][/url]. Click it.
 

Posts:781
Registered: 5/1/01
Re: help on programming multi-thread - please  
Jul 24, 2004 3:30 PM (reply 7 of 17)



 
thanks for the tutorial.
the server starts a thread for each client request, and there is only one instance of the servlet that will be handling the request. what is the difference between thread and instance? why multiple threads and not multiple instances?is it because it is too expensive to instantiate an instance than a thread?

in case of multi threads, is the instance members shared among the threads? is that why u were suggesting not to have member variables.
 

Posts:37,103
Registered: 3/30/99
Re: help on programming multi-thread - please  
Jul 24, 2004 4:12 PM (reply 8 of 17)



 
thanks for the tutorial.
the server starts a thread for each client request,

Not necessarily, but that's one valid model.

and there is only one instance of the servlet that
will be handling the request. what is the difference
between thread and instance?

They're two totally different things. A thread is just an independent execution path--almost like starting another program. You start a thread by creating a Thread object and calling its start method.

An instance is any object that's instantiated.
String s = "abc";Foo foo = new Foo(); 
I have an instance of String and an instance of Foo.

why multiple threads and
not multiple instances?is it because it is too
expensive to instantiate an instance than a thread?

It's not really a "multiple threads vs. multiple instances" question. You could have one thread and one instance, many threads and one instance, one thread and many instances, or many threads and many instances. (i.e., instances of your servlet)

You have to have multiple threads if you want to process multiple requests simultaneously. Wy not give each thread its own instance of your servlet class? Because it's unnecessary and wasteful, I guess. A servlet's job is just to pass incoming requests from the container on to the business logic that handles them, and then pas the results of that business logic back to the container. As such, a servlet doesn't need to maintain state (member variables) and so there's no need for multiple thread NOT to share one servlet instance.


in case of multi threads, is the instance members
shared among the threads? is that why u were
suggesting not to have member variables.

Yes.
 

Posts:781
Registered: 5/1/01
Re: help on programming multi-thread - please  
Jul 25, 2004 9:06 AM (reply 9 of 17)



 
thanks man, u have been an outstanding teacher to me. sometimes, it is easier to understand the stuff from a experienced person than from reading a large book.
what is the most important thing(s) that i should be aware of when programming thread? do u have any tip(s) to share? thanks.
 

Posts:37,103
Registered: 3/30/99
Re: help on programming multi-thread - please  
Jul 25, 2004 10:36 AM (reply 10 of 17)



 
thanks man, u have been an outstanding teacher to me.
sometimes, it is easier to understand the stuff from a
experienced person than from reading a large book.
what is the most important thing(s) that i should be
aware of when programming thread? do u have any tip(s)
to share? thanks.

You're welcome. Glad to be ofhelp.

I don't know that there is a single most important thing. There are a lot of issues you need to be aware of, and they're all important. As for tips, I'd suggest gettng familiar with the [url http://java.sun.com/docs/books/jls/second_edition/html/j.title.doc.html]JLS[/url], especially Chapter 17. Therea rea assumptions you make with single-threaded code that don't hold in a multithreaded envrionment. You need to get a real handle on what volatile and synchronized do.
 

Posts:781
Registered: 5/1/01
Re: help on programming multi-thread - please  
Jul 25, 2004 11:09 AM (reply 11 of 17)



 
ever since i started this topic, i have been reading some online information about thread, some of them give examples that have instance variables, one of them is used for stopping a thread. in the doc from http://java.sun.com/docs/books/tutorial/essential/threads/lifecycle.html, it has the run method as follow :
public void run() {    Thread myThread = Thread.currentThread();    while (clockThread == myThread) {        repaint();        try {            Thread.sleep(1000);        } catch (InterruptedException e){            // the VM doesn't want us to sleep anymore,            // so get back to work        }    }}


clearly it is checking the clockThread variable for state information in order to stop the thread. the stop method :
public void stop() {    // applets' stop method    clockThread = null;}

set the state to null. some questions come to my mind. i understand that it is not a good idea to use instance variable, but the sample given uses it as an indicator weather to stop the thread or keep it running. is there a reason for this ? and when would this stop method ever be called to reset the clockThread to null so that the thread will stop. i guess whatever starts the thread can also calls the stop method to stop it. Is it because of the looping, somehow it needs to be terminated. and checking clockThread is the only way.
 

Posts:37,103
Registered: 3/30/99
Re: help on programming multi-thread - please  
Jul 25, 2004 12:01 PM (reply 12 of 17)



 
i understand that it is not a good idea to use
instance variable, but the sample given uses it as an
indicator weather to stop the thread or keep it
running. is there a reason for this ?

It's not that instance variables are universally bad. You dont want to use them in a servlet, because the servlet needs to be called in a multithreaded environment and you can't synchronize for performance reasons (and a servlet doesn't really need to maintain state anyway).

In the general case of creating your own threads, a common idiom is to use a loop that checks a flag, and then either does a unit of work or exits. "Am I done? No. Okay, do a unit of work. Am I done? No. Okay, do a unit of work. Am I done? Yes. Exit the loop."

But that doesn't apply to your severlet. Your severlet is not a Thread or a Runnable. The instance variable flag just doesn't aply to your servlet, because it just processes a single request as it comes in--you don't have to have a way to tell it to stop, because it's not a thread. The threading is managed by the servlet container.
 

Posts:781
Registered: 5/1/01
Re: help on programming multi-thread - please  
Jul 25, 2004 12:04 PM (reply 13 of 17)



 
sorry, i guess i was a little mixed up with servlet and thread. thanks
 

Posts:781
Registered: 5/1/01
Re: help on programming multi-thread - please  
Jul 26, 2004 5:57 AM (reply 14 of 17)



 
hi jverd
just have one more question to ask about synchronization in jsp, and i will stop bugging you for a while.
let's say in the jsp i need to display/update/insert information from/to DB. because of the concurrency, i will need to synchronize the access so that each request to the page has the correct information. most samples i have seen don't have the syn on the page. i was wondering if the synchronization is done somewhere else other than in the page. is it a good practice or idea to have jdbc stuff coded in the jsp? thanks.
 
This topic has 17 replies on 2 pages.    1 | 2 | Next »