Using SingleThreadModel

Hello
I'm reading about ways to make my servlets thread safe. As I have learned , there are two main ways,
using synchronized block around some code or using SingleThreadModel. (Please correct me if wrong).
My servlets work in an environemnt where data of database is frequently updated, therefore in their doPost() or doGet() method they stablish a connection to database, get the required data, close the connection and use an arraylist to display the result. (Again please feel free to add your comments on how to best go about this)
Inside servelts, I do not call any classes (all code of access db is directly inside servelt) and just use some local variables for loops and temp storage and such.
I appreciate your help with two points:
1. I would like to use SingleThreadModel for a servlet that updates the database; I have read in
http://www.exampledepot.com/egs/javax.servlet/NoMulti.html?l=rel
that this is not sufficeint to properly synchronize shared state and developer should do it. Could you please explain what is meant by shared state and how I can do that ?
2. For servlets that just run queries, I think I should use synchronized block around some code, but I am not sure which parts of code should be contained in it ?
Moreover , it is advised not to synchronize doPost or doGet methods ...
Could you please help me understand what is the best strategy to choose to make sure performance is good and all operations are thread safe?
Thank you very much in advance
Nicole

Use of the SingleThreadModel is discouraged for various reasons. I would not recommend that path.
Probably need more information about what is needed to be synchronized.
For query only, I would imagine that no synchronization is necessary.
With regards to thread safety/synchronization/consistency of data there are a few levels to consider.
1 - Servlet level.
The standard model is that a servlet is instantiated once, and then runs multiple threads through its "service" method.
The easiest way to have a threadsafe servlet is to use local variables only. Class attributes in the servlet would be shared by all threads accessing that class, and thus would not be threadsafe.
public class MyServlet extends HttpServlet{
  private String nonThreadSafeVariable = "hello";
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, java.io.IOException{
    String threadSafeVariable = "world";
}So if each call to your servlet obtains its own database connection (preferably from a connection pool) runs its queries and closes/returns it, you will not have concurrency issues there.
In this simple model you don't need to worry about synchronizing things.
2 - Making it more complicated. Data/Transaction level.
If you need to ensure read/write consistency - ie read a value from the database, and then write back an updated value without someone getting that same "before" value (updating someones bank account is the classic example) then you need to synchronize around the whole operation.
So that you lock, read, write unlock. That is probably best done with a database transaction / lock. If doing it in java, then I would implement this in a bean layer outside of the servlets, and have the servlets call that layer.
Hope this helps some,
evnafets

Similar Messages

  • When do we use SingleThreadModel ?

    when do we use SingleThreadModel of Servlet ? Is there any practical situation where this could be used ?

    I think there are specific requirements that would need the SingleThreadModel just like there will be need for Singleton classes. An example is the Event Dispatch Thread used in swing.Err, no. This is complete nonsense. SingleThreadModel is an interface in the Servlet API. Servlets don't use Swing.
    @OP: SingleThreadModel is 'deprecated as of Servlet API 2.4, with no direct replacement'. That was in 2004. So the answer is that you don't use it at all.

  • When is it a good idea to use SingleThreadModel?

    Can anyone tell me a concrete example of when the SingleThreadModel is a better idea then simply using the default behaviour and synchronizing critical code?
    Thanks,

    I certainly cannot. It's inefficient and only helps in single-threading instance variables, which you shouldn't be using to pass info between methods anyway. You still need to synchronize on external resources. Besides that, it's deprecated in Servlet spec 2.4. Don't ever use it.

  • IPlanet 4.0 SP9 & SingleThreadModel

    Hi:
    We are developping a web server using iPlanet 4.0 SP9
    and servlets. The server will server several users at
    same time, for this reason, we are using the interface
    SingleThreadModel, in order to avoid problems related to
    the use of threads and multiple users.
    But, this seems not to work properly. When two users are connected to our server, the second one must wait for
    the first one. In other words, if the first user executes
    an option that take a lot of time to be completed and
    meantime the second user tries to use the web server, he
    will wait until the first user's task was finished. The
    web server looks like to be locked.
    We are thinking about the iPlanet is misconfigured.
    Any idea, remark, tip, etc.?
    Thanks in advance.
    Alberto

    My advice - don't use SingleThreadModel. They shouldn't have provided this in the first place and here's why
    3.2 Number of Instances
    In the case of a servlet that implements the SingleThreadModel interface, the servlet container
    may instantiate multiple instances of that servlet so that it can handle a heavy request load while
    still serializing requests to a single instance.
    3.2.1 Note about SingleThreadModel
    The use of the SingleThreadModel interface guarantees that one thread at a time will execute
    through a given servlet instance�s service method. It is important to note that this guarantee only
    applies to servlet instance. Objects that can be accessible to more than one servlet instance at a
    time, such as instances of HttpSession, may be available to multiple servlets, including those
    that implement SingleThreadModel, at any particular time.
    Here's a simple example: if you use a text file for storing/retrieving data and the server decides to instantiate another instance of your single threaded servlet - guess what's gonna happen?
    Always use the normal multi-threaded servlets and develop them properly for multiple thread use.

  • Implementing SingleThreadModel on a Servlet

    Can someone explain to me what are the implications of implementing SingleThreadModel on a Servlet?
    I have this servlets that serves images "on-the-fly" to the browsers, my first version was not implementing SingleThreadModel and was accessed mainly by XMLHttpRequest, assynchronously, but then i only had to get a image at a time to a given page.
    Now i have several images on a page, so it was starting giving problems, so i remove the assynchronous access and implemented SingleThreadModel, it seems ok but i wonder what the implications are.
    Should i create two servlets for one/many images? Should i not implement SingleThreadModel and take care of the threads myself? Or is ok using SingleThreadModel ?
    Thanks all

    The implications are that you make that servlet a bottleneck, because requests to it cannot run in parallel. The fix for this is not to handle threads for yourself. That is what the servlet container is for. The fix is to modify your servlet so that it is thread-safe. The first major step here is to stop using static and instance variables to store data, although I can't imagine why a servlet that serves out an image file would need to use variables in that way. There may be more complexities but if you understand threading properly you should be able to track them down.

  • Mms to servlet general methodology?

    I am working on a project that involves mobile device to servlet communication. It allows doctors to submit voice-recorded requests for medical information. The recorded data is run thru speech recognition and nlp software and used to generate various back-end queries for data. We are fairly clear about how to do this using local wi-fi connection to a server via http. We're also interested in using mobile messaging facilities for the same purpose. I understand that mobile messaging (text and multimedia) involves going out to a wireless gateway from the phone, and from there to a phone carrier's messaging center server (whose usual purpose is just to send the message back out to another wireless phone user). Does anyone know of methods whereby our application server could gain access to the wireless message, either by linking to the carrier's messaging center, or by any other means? Any tutorials or know of any existing projects that use a mobile phone message to send data to an application server? Thanks in advance...

    Locutus wrote:
              > Is there a way to configure weblogic to allow more than 2 concurrent
              > accesses from the same client to the same servlet with the same session id?
              Servlets are concurrent by default regardless of the session unless you're
              using SingleThreadModel. It's your job to make sure shared data (instances
              stored in the session qualify) is thread-safe.
              Alex
              

  • Which is thread safe

    If I implement SingleThreadedModel in a servelt which are all thread safe?
    Request object, response object, instance variables,class variables( by the by can i have class variables in a Servlet ? how/where it will be used?)

    If you use SingleThreadModel, everything will be thread safe, because you are spawning one instance of the servlet, for every request. This WILL NOT scale well if you have many users at once.
    With regard to what is thread safe in a normal servlet, I believe
    request
    response
    session
    variables local to functions
    NOT safe:-
    class variables - these will be shared by multiple instances.

  • Scope of instance variables in servlets..

    Hi all,
              Sorry for asking a dumb question..
              What is the scope of instance variables in a servlet? Is the scope is
              limited to thread?
              In other words, in the following example, i am setting "testStr", in one
              request and when i tried to access the same instance variable from another
              request, i am getting it as null. Does it mean instance variable is limited
              to that particular thread/request?
              thanks in advance..
              -ramu
              

    Oops ... I had misunderstood and had the problem backwards ;-)
              > Is it known behavior? With registered servlet its working fine (a
              > instance variable is shared by all requests)
              I believe so; I typically deploy in a WAR so have not seen the problem that
              you describe. Servlets can be reloaded, so what you saw could have been
              caused bye a date/time mismatch between the .class file and the server's
              current time. On the other hand, that could be how WebLogic works.
              Peace,
              Cameron Purdy
              Tangosol, Inc.
              http://www.tangosol.com
              +1.617.623.5782
              WebLogic Consulting Available
              "Ramu" <[email protected]> wrote in message
              news:[email protected]...
              > Hi Purdy,
              >
              > I got it. I am testing the servlet as a unregistered servlet, which is
              > creating instance for every new request!!!, which created this whole
              > confusion. Is it known behavior? With registered servlet its working fine
              (a
              > instance variable is shared by all requests)
              >
              > > What theory? ;-) Instance variables are on the object, and the object
              can
              > > be used by multiple threads, thus allowing multiple threads to access
              the
              > > same instance variables.
              > what i mean by theory here is, all instance variables in servlet should
              be
              > shared by all requests. Now i got it sir.
              >
              > Thank you..
              > -ramu
              >
              >
              > >
              > > Peace,
              > >
              > > --
              > > Cameron Purdy
              > > Tangosol, Inc.
              > > http://www.tangosol.com
              > > +1.617.623.5782
              > > WebLogic Consulting Available
              > >
              > >
              > > "Ramu" <[email protected]> wrote in message
              > > news:[email protected]...
              > > > Hi,
              > > >
              > > > > No, an instance variable in a servlet class is not limited to a
              > thread.
              > > > There
              > > > > is exactly one copy of the servlet created in memory and all
              requests
              > > pass
              > > > > through the same instance, thus sharing any instance variables. A
              > > couple
              > > > of
              > > > > things to remember:
              > > > I totally agree with you, But i am wondering why my sample servlet(i
              am
              > > > attaching the file) is not sharing the instance variables across
              > > > threads/reqs. (in 1st request set some string to "testStr" instance
              > > > variable, in next request if you read the same instance variable, you
              > will
              > > > get null!!)
              > > > Our current code is having instance variables. But right now we are
              not
              > > > getting any problems. But as per theory, instance variables should be
              > > shared
              > > > across threads/requests..
              > > >
              > > > Any how we are changing our code to remove all instance variables.
              > > >
              > > > thanks,
              > > > -ramu
              > > >
              > > > >
              > > > > 1.) Using instance or class variables in servlets that are not
              > read-only
              > > > is not
              > > > > a good thing to do. This makes the servlet not thread-safe. To
              > > maintain
              > > > > variables across requests, sessions, etc., use the servlet-defined
              > > objects
              > > > to
              > > > > store the state (e.g., request, session, etc.).
              > > > >
              > > > > 2.) If you modify the servlet class on disk, WebLogic will reload
              the
              > > > servlet
              > > > > class thus discarding the old instance and creating a new one (of
              > > course,
              > > > this
              > > > > depends on some configuration parameters for servlet reloading).
              > > > >
              > > > > Hope this helps,
              > > > > Robert
              > > > >
              > > > > Ramu wrote:
              > > > >
              > > > > > Hi,
              > > > > > thanks for quick reply.
              > > > > > I am not at all using SingleThreadModel. See the following code.
              > > > > > In first request i am passing "abc" value to testStr. But in
              second
              > > > request,
              > > > > > I am getting null for testStr in second request. It looks like
              (for
              > > me)
              > > > for
              > > > > > non single threaded model also, scope of instance variables is
              > > limited
              > > > to
              > > > > > Thread/Request.. But as per theory, because its not single
              threaded
              > > > model,
              > > > > > only one instance should be there AND testStr(instace variables)
              > > should
              > > > be
              > > > > > shared across the all threads. But i am not able see that
              behaviour
              > > > here.
              > > > > > But if declare instance variable as static, o am able to share
              it
              > > > across
              > > > > > all threads/requests.
              > > > > >
              > > > > > note:
              > > > > > From browser i am setting testStr to "abc" with URL like
              > > > > > "localhost/test1?testStr=abc"
              > > > > > And 2nd req from browser is like "localhost/test1" (on server
              > output
              > > i
              > > > am
              > > > > > getting null for testStr)
              > > > > >
              > > > > > Any ideas?
              > > > > >
              > > > > > thanks,
              > > > > > -ravi
              > > > > >
              > > > > > import java.io.*;
              > > > > > import javax.servlet.*;
              > > > > > import javax.servlet.http.*;
              > > > > >
              > > > > > public class test1 extends HttpServlet
              > > > > > {
              > > > > > public String testStr;
              > > > > >
              > > > > > public void doGet (HttpServletRequest req, HttpServletResponse
              res)
              > > > > > throws ServletException, IOException
              > > > > > {
              > > > > > doPost(req, res);
              > > > > > }
              > > > > >
              > > > > > public void doPost (HttpServletRequest req,
              HttpServletResponse
              > > res)
              > > > > > throws ServletException, IOException
              > > > > > {
              > > > > > try {
              > > > > > res.setContentType("text/html");
              > > > > > PrintWriter out = res.getWriter();
              > > > > > if(req.getParameter("testStr") != null)
              > > > > > {
              > > > > > testStr = req.getParameter("testStr");
              > > > > > System.out.println("set testStr = " + testStr);
              > > > > > }
              > > > > > else{
              > > > > > System.out.println("get testStr = " + testStr);
              > > > > > }
              > > > > >
              > > > > > }
              > > > > > catch(Exception e){
              > > > > > e.printStackTrace();
              > > > > > }
              > > > > >
              > > > > > }
              > > > > > }
              > > > > >
              > > > > > "Cameron Purdy" <[email protected]> wrote in message
              > > > > > news:[email protected]...
              > > > > > > Yes or no, depending on if your servlet implements
              > > SingleThreadModel.
              > > > > > >
              > > > > > > See the servlet 2.2 spec for documentation on how many instances
              > of
              > > a
              > > > > > > servlet will be created. See the doc for the SingleThreadModel
              > > > interface.
              > > > > > >
              > > > > > > Peace,
              > > > > > >
              > > > > > > --
              > > > > > > Cameron Purdy
              > > > > > > Tangosol, Inc.
              > > > > > > http://www.tangosol.com
              > > > > > > +1.617.623.5782
              > > > > > > WebLogic Consulting Available
              > > > > > >
              > > > > > >
              > > > > > > "Ramu" <[email protected]> wrote in message
              > > > > > > news:[email protected]...
              > > > > > > > Hi all,
              > > > > > > >
              > > > > > > > Sorry for asking a dumb question..
              > > > > > > >
              > > > > > > > What is the scope of instance variables in a servlet? Is the
              > scope
              > > > is
              > > > > > > > limited to thread?
              > > > > > > >
              > > > > > > > In other words, in the following example, i am setting
              > "testStr",
              > > in
              > > > one
              > > > > > > > request and when i tried to access the same instance variable
              > from
              > > > > > another
              > > > > > > > request, i am getting it as null. Does it mean instance
              variable
              > > is
              > > > > > > limited
              > > > > > > > to that particular thread/request?
              > > > > > > >
              > > > > > > > thanks in advance..
              > > > > > > >
              > > > > > > > -ramu
              > > > > > > >
              > > > > > > >
              > > > > > > >
              > > > > > >
              > > > > > >
              > > > >
              > > >
              > > >
              > > >
              > >
              > >
              >
              >
              

  • What substitution should be used for the depricated SingleThreadModel?

    This class has been depricated, how to substitude it?
    In general, how to find out what a substitution for a depricated class is?
    Thanks,

    maybe you can implement a interface ComponentListener as well as ComponentAdapter with your topmost Table.
    for example:
    toptable.addComponentListener(
    new ComponentAdapter(){
    public void componentResized(ComponentEvent e){
    table1.setSize(....);
    table2.setSize(....);
    /*Optionally, you must also call function revalidate
    anywhere;*/
    );

  • Global data in a servlet using iPlanet Web Server

    Our configuration is an Applet->Servlet->JNI->C/C++ code.
    We have C code that does a number of lengthy mathematical calculations. This C code not only uses its own global variables but, it is also comprised of numerous subroutines that all call each other, reading and writing global C variables as they go. These globals are all isolated to the C code shareable object (.so) library that is included using the LoadLibrary call when the servlet is initialized.
    The problem is that in a multi-user environment (3-5 simultaneous users) we need to have each user have their own "copy" of the servlet (and the C code) so that users will not be accessing each other's global data. We can NOT have only one copy of the C code and define it as synchronized because the calculations that are performed can take a very long time and we can not hold off user requests while the firs user finishes.
    Our hope is that there is a way to configure the iPlanet Web server such that each new user that starts up a copy of the Applet/Servlet combination will get their own "space" so that they can work independently of any other user. We have at most 20 users of this system and only 3-5 simultaneous users so we should not have a problem with memory or CPU speed.
    If anyone has a solution, I would greatly appreciate it!

    The C library is shareable. But you don't want it to be shared. That's your question summarized, isn't it?
    You probably can't prevent it from being shared, so to prevent multiple use of it you would have to queue up the requests to be done one at a time. WynEaston's suggestion of having the servlet implement SingleThreadModel would help, but I believe the servlet spec allows servers to run multiple copies of a servlet that does that (as opposed to running a single copy in multiple threads).
    Your other alternative is to rewrite the math in Java, or at least in some object-oriented language where you don't need global variables (which are the source of your problem). All right, I can already hear you saying "But that wouldn't be as fast!" Maybe not, but that isn't everything. Now you have a problem in queueing theory: do you want a single server that's fast, but jobs have to wait for it, or do you want multiple servers that aren't as fast, but jobs don't have to wait? That's a question you would have to evaluate based on the usage of your site, and it isn't an easy one.

  • Connect access using JDBC

    Hi
    I need to write a little server program to pass in SQL statement sent from the client and perform the statement and return the result to the client. I want to server to be able to support more than one access at a time so I will be using thread. It is where I am stuck because am I allowed to use concurrent access to database through JDBC APIs? By the way I am very new to threading etc. so any help and suggestions or directions to other resources will be appreciated.

    if u are using servlet then in class where u are writing service() just implement interface SingleThreadModel
    write your code to make commection in that service()
    java JVM automatically takes care of it ie. multiple thread
    or another way is to use Connection Pooling
    bye
    vijaysingh

  • What is the use of Marker Interfaces?

    What is the use of marker interfaces?
    As it is not having any methods or fileds what is the benefit I will get by implementing those interfaces?
    Servlet implements SingleThread
    What it will do behind the scenes exactly as singleThread model is marker interface

    The use of marker interfaces is to act as markers (shock horror)
    It is quite a common way to tell a program what a class can/can't do: Cloneable, Serializable etc etc
    This doesn't change the functionality of the class itself, but is more an indication as to what can be done with this class.
    In this case the servlet container can then tell whether or not it implements the interface, and can treat it accordingly. Implementing this interface tells the container you want it to run this servlet in singleThreaded mode.
    Thats all there is to it.
    It would be along the lines of
    Servlet servlet = loadServlet("...")
    if (servlet instanceof SingleThreadModel){
    // Single threaded servlet - start new process for it
    else {
    // regular servlet - reuse existing object.

  • Number of initial instances in SingleThreadModel

    Just out of curiousity : When a servlet that implements the
              SingleThreadModel first is accessed, a number of instances are created.
              If I log every call to init(), I see 6 calls. However, WLS seems to be
              using only 5 of these instances. What is the 6'th instance used for ?
              jo
              

    Hi David,
    In order to find the total numbers of reports in the Enterprise fire the following query from the Query Builder tool.
    SELECT
    Count(SI_ID)
    FROM
    CI_INFOOBJECTS
    WHERE
    SI_KIND = u2018CrystalReportu2019
    The queries above will return the total count of the CR reports which are present in the Enterprise.
    In case you would like to find the WebI Or DeskI reports reports then use the following in the where clause respectively SI_KIND = u2018webiu2019 and SI_KIND = u2018fullclientu2019
    I hope this helps you.
    Regards,
    Prashant

  • Marker interface use

    In which case Marker interface is getting use plz tell

    Marker Interfaces are giving specification to the JVM about the implementing classes.
    One of the features of the Java programming language is that it mandates a separation between interfaces (pure behavior) and classes (state and behavior). Interfaces are used in Java to specify the behavior of derived classes. Often you will come across interfaces in Java that have no behavior. In other words, they are just empty interface definitions. These are known as marker interfaces. Marker interfaces are also called "tag" interfaces since they tag all the derived classes into a category based on their purpose.
    Some examples of marker interfaces in the Java API include: -
    Java.lang.Cloneable
    A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class.
    java.io.Serializable
    Serialization is nothing but s saving the state of an object to persistent storage as byte stream. Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable. To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime.
    java.util.EventListener
    A tagging interface that all event listener interfaces must extend.
    java.rmi.Remote
    The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine. Any object that is a remote object must directly or indirectly implement this interface. Only those methods specified in a "remote interface", an interface that extends java.rmi.Remote are available remotely.
    Javax.servlet.SingleThreadModel
    Ensures that servlets handle only one request at a time. This interface has no methods. If a servlet implements this interface, you are guaranteed that no two threads will execute concurrently in the servlet's service method.
    Java.util.RandomAccess
    This Marker interface used by List implementations (ArrayList, Vector) to indicate that they support fast (generally constant time) random access. The primary purpose of this interface is to allow generic algorithms to alter their behavior to provide good performance when applied to either random or sequential access lists.
    Javax.ejb.EnterpriseBean
    The EnterpriseBean interface must be implemented by every enterprise Bean class. It is a common superinterface for the SessionBean, EntityBean and MessageDrivenBean interfaces.
    Reference From Sun Documentation

  • SingleThreadModel and amount of servlet instances ??

    Hi !
              Is there anybody who knows how to determine amount of servlet instances in
              wl5.1 if the servlet is implemented in SingleThreadModel ?
              P.asi
              

    Yup, I remember somebody mentioned that initial size is hardcoded to 5 and
              max size to 20.
              Robert Patrick <[email protected]> wrote:
              > I am not sure if a recent Service Pack has changed this or not but the
              > original implementation in WLS 5.x was that the SingleThreadModel always used
              > a fixed number of servlet instances (5, I think...).
              > Pasi Lukkarinen wrote:
              >> Hi !
              >>
              >> Is there anybody who knows how to determine amount of servlet instances in
              >> wl5.1 if the servlet is implemented in SingleThreadModel ?
              >>
              >> P.asi
              Dimitri
              

Maybe you are looking for

  • How to copy the standarad function module

    hi,       i wants to copy the standard function module which are not rfc enabled. for that one i copied standard one and modified the attributes to rfc enabled. but it was giving the errors "You can only use LIKE and TYPE to specify types in RFC", ho

  • 10.3.9 Internet issues

    Hi All i have been trawling through the fourms and still cannot find a solution to my iMac internet issues. I have done a complete format and reinstall of Mac OS X 10.3.9 (to be fair i downloaded update on another computer and instelled via USB stick

  • Masked QuickTime movies not displaying correctly...

    Hi there, I'm still a relative novice with Keynote, but am quickly learning that this is a seriously great application! I haven't encountered any real problems so far, except the one I'm about to describe - and I'd really appreciate any help you coul

  • Using Thunderbolt Display with Alienware Laptop

    I want to also use my thunderbolt display with a m18x alienware laptop which has HDMI out and a mini display port.  Is there any way I can use this display with this laptop either directly or with an adapter? Thanks

  • How to deselect a select table column?

    Hi! I've implemented a table with selectable columns. This is working fine, but I'm not clear how to deselect the selected table column with code. How to do so? Thanks for any hints! Peter