Is abap thread safe? Some question in Singleton pattern in ABAP

Hi Grus,
I have a very basic question but really make me headache...
Recently I am learning the design pattern in ABAP and as you know in JAVA there is a key word "Synchronized" to keep thread safe. But in ABAP, I didn't find any key words like that. So does that mean ABAP is always a single thread language? And I found that there is a way looks like "CALL FUNCTION Remotefunction STARTING NEW TASK Taskname DESTINATION dest" to make multi-thread works. As you can see it use the destination, so does that mean actually the function module is always executed in a remote system, and in every system, it is always single thread?
Could you help me on the question? Thanks a lot, grus
And here comes up to my mind another question...It's a little bit mad but I think it may works....What if I set every attribute and method as static in the singleton class...Since as you can see it is already a singleton so every attribute in it should be only one piece. So then I don't even need to implement a get_instance( ) method to return the instance. Just call "class_name=>some_method( )" directly then singleton is achieved...What do you think?
BR,
Steve

Steve,
I've the same question, few days ago I tried to use the singleton in ABAP. In Java programming is possible to use the same reference in two sessions or programs, sharing attributes, methods and all data, but I could not do in ABAP.
In my test I created a program with one global class using the singleton pattern, so I expected that when I run my program and see the reference returned after the get_instance method it should be equal to the same program run in another session, but the ABAP will create a new reference and instantiate again.
So I deduced that the only way to share it between sessions in ABAP is using the ABAP Shared Memory Objects.
I can be wrong, but I think that ABAP use a thread by user session (Each window) and we can't change it.
Best regards.

Similar Messages

  • A question about singleton pattern

    Will a singleton instance be a bottleneck of an application when many client address this instacne?
    and How can I do to deal with this problem?
    help me!

    Unless the singleton has synchronized methods or blocks of code that are synchronized there should be no bottle neck, as multi threads can access it at the same time.

  • Is singleton thread safe?

    hello all,
    please help me by answering these questions?
    singleton patterns calls for creation of a single class that can be shared between classes. since one class has been created
    Can singletons be used in a multithreaded environment? is singleton thread safe?
    Are threading problems a consequence of the pattern or programming language?
    thank you very much,
    Hiru

    Hi,
    Before explaining whether a singleton is thread safe
    e i want to explaing what is thread safe here
    When multiple threads execute a single instance of a
    program and therefore share memory, multiple threads
    could possibly be attempting to read and write to the
    same place in memory.If we have a multithreaded
    program, we will have multiple threads processing the
    same instance.What happens when Thread-A examines
    instance variable x? Notice how Thread-B has just
    incremented instance variable x. The problem here is
    Thread-A has written to the instance variable x and
    is not expecting that value to change unless Thread-A
    explicitly does so. Unfortunately Thread-B is
    thinking the same thing regarding itself; the only
    problem is they share the same variable.
    First method to make a program threadsafe-: Avoidance
    To ensure we have our own unique variable instance
    for each thread, we simply move the declaration of
    the variable from within the class to within the
    method using it. We have now changed our variable
    from an instance variable to a local variable. The
    difference is that, for each call to the method, a
    new variable is created; therefore, each thread has
    its own variable. Before, when the variable was an
    instance variable, the variable was shared for all
    threads processing that class instance. The following
    thread-safe code has a subtle, yet important,
    difference.
    second defense:Partial synchronization
    Thread synchronization is an important technique to
    know, but not one you want to throw at a solution
    unless required. Anytime you synchronize blocks of
    code, you introduce bottlenecks into your system.
    When you synchronize a code block, you tell the JVM
    that only one thread may be within this synchronized
    block of code at a given moment. If we run a
    multithreaded application and a thread runs into a
    synchronized code block being executed by another
    thread, the second thread must wait until the first
    thread exits that block.
    It is important to accurately identify which code
    block truly needs to be synchronized and to
    synchronize as little as possible. In our example, we
    assume that making our instance variable a local
    variable is not an option.
    Third Defence:--Whole synchronization
    Here u should implement an interface which make the
    whole class a thread safe on or synchronized
    Thre views are made by Phillip Bridgham, M.S., is a
    technologist for Comtech Integrated Systems.I'm
    inspired by this and posting the same hereWas there a point in all of that? The posted Singleton is thread-safe. Furthermore, some of that was misleading. A local variable is only duplicated if the method is synchronized, a premise I did not see established. Also, it is misleading to say that only one Thread can be in a synchronized block of code at any time because the same block may be using different monitors at runtime, in which case two threads could be in the same block of code at the same time.
    private Object lock;
    public void doSomething() {
        lock = new Object();
        synchronized(lock) {
            // Do something.
    }It is not guaranteed that only one Thread can enter that synchronized block because every Thread that calls doSomething() will end up synchronizing on another monitor.
    This is a trivial example and obviously something no competent developer would do, but it illustrates that the statement assumes premises that I have not seen established. It would be more accurate to say that only one Thread can enter a synchronized block so long as it uses the same monitor.
    It's also not noted in the discussion of local variables vs instance variables that what he says only applies to primitives. When it comes to actual Objects, just because the variable holding the reference is unique to each Thread does not make use of it thread-safe if it points to an Object to which references are held elsewhere.

  • Thread-safe Singleton

    Hi,
    I want to create a thread safe singleton class. But dont want to use the synchronized method or block. One way i could think of was initializing the object in static block. This way the instance will be created only once. But what if instance becomes null after some time. How will it get initialized again. Can anyone help me in creating a thread safe singleton class.
    Also i would really really appreciate if some one can point me to a good tutorial on design patters, I searched on google.. Found many.. But not finding any of them satisfying.
    Thanks

    tschodt wrote:
    Balu_ch wrote:
    kilyas wrote:
    Look into the use of volatile instead of synchronized, however the cost of using volatile is comparable to that of synchronizingCan you please explain in detail Google can.
    Google ( [java volatile vs synchronized|http://www.google.com/search?q=java+volatile+vs+synchronized] ).
    Hi, I think we need to use both (volatile and synchronized). Can some please explain how "volatile" alone can be used to ensure thread safe singleton? Below is the code taken from wikipedia
    public class Singleton {
       // volatile is needed so that multiple thread can reconcile the instance
       // semantics for volatile changed in Java 5.
       private volatile static Singleton singleton;
       private Singleton()
       // synchronized keyword has been removed from here
       public static Singleton getSingleton(){
         // needed because once there is singleton available no need to acquire
         // monitor again & again as it is costly
         if(singleton==null) {
           synchronized(Singleton.class){
              // this is needed if two threads are waiting at the monitor at the
              // time when singleton was getting instantiated
              if(singleton==null)
              singleton= new Singleton();
       return singleton;
    }

  • [SOLVED] Singleton thread safe

    If I have a singleton object where all instance and class variables are thread safe objects, is that object thread safe?
    Edited by: 888903 on Oct 3, 2011 8:30 PM

    888903 wrote:
    If I have a singleton object where all instance and class variables are thread safe objects, is that object thread safe?First, "all instance and class variables are thread safe objects" cannot be true, because variables are not objects. Presumably you meant to say that these variables refer to threadsafe objects.
    As for your question, no, you cannot say that a given object is threadsafe just because all its member variables are. It depends on the semantics of your class, and what it needs to be atomic. For example, take the following class:
    public class Person {
      private String firstName;
      private String lastName;
      public String getName() {
        return firstName + " " + lastName;
      public void updateName(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }Here, we have a class like what you describe. (The fact your case involves a singleton is irrelevant.) My String member variables are threadsafe, but my Person class is not. If I start with "Joe Smith" and then later I call person.updateName("Fred", "Jones"), another thread could call getName() after I've updated the first but before the last, so he'd see "Fred Smith", which is incorrect. He should see only "John Smith" or "Fred Jones", not an intermediate value.

  • Some questions on interrupts, threads etc

    Havng gone through some documentation on interrupt, kernel level threads etc in WDF, I got a couple of questions:
    1)  Can a hardware interrupt be preempted by another interrupt in a single processor system?
    2)  What exactly is the difference between thread preemption and thread interrupt? Doesnt both mean stopping the current thread and putting it aside?
    3)  When an iterrupt is handled by an ISR, does the ISR always have to  schedule  a DCP? If the ISR itself can handle the interrupt, is the DPC needed?
    4) I understand that spin locks are used for synchronisation at IRQL <=DISPATCH_LEVEL. EVT_WDF_IO_QUEUE_IO_WRITE works at <= DISPATCH_LEVEL. If I set Synchronisation scope of a write queue as SynchronisationScopeQueue, should I still go for a spin
    lock, if the write callback and say an ioctl callback uses a shared resource?
    5 )Kernel dispatcher objects are mutex, timer, event, semaphore etc. But If i use a fast mutex or guarded mutex or oridinary mutex using say, KeAcquireFastMutex() isnt that then a kernel dispatcher object? What this distinction?  Why should we go explicitly
    go for kernel dispatcher object?
    6) How can timers be used for kernel level synchronisation? How different is this from timers created using WdfTimerCreate()?
    7)  It is said that "Never wait on a kernel dispatcher object in any driver routine that can be called at IRQL>=DISPATCH_LEVEL.". Does it mean
    we should not use synchronisation mechanisms in this level? Or if we can use, should the thread try to acquire a lock with  a zero wait time? And proceed if it could acquire the lock and return if the lock was not acquired?
    8) I understand that in order to execute an interrupt, a driver does not create any special threads but use a thread that happens to be running at the moment( arbitrary thread ) . My question is, in what way is this accomplished? What aspect of the arbitrary
    thread is the interrupt using ? The arbitrary thread must obviously have been written for another purpose.

    To answer the questions:
    #1   An interrupt service routine (ISR) running a lower IRQL may be interrupted by another ISR running at a higher level.
    #2   Having never heard of a thread interrupt, all I can say here is that a thread may be pre-empted for a lot of reasons.
    #3   An ISR does not have to schedule a DPC unless it needs to do work that it cannot do at high IRQL.
    #4   Assuming that the Write and IOCTL are on seperate queues, yes you need a a lock to protect shared resources.
    #5   As the name implies kernel dispatcher objects allow scheduling (i.e. dispatching of another thread), while things like spinlocks do not. 
    #6    Timers are just another dispatching object, i.e. one can wait on them the same way one waits on a mutex or a semaphore.  A WDF TIMER is basically a wrapper around a regular timer to take care of some of the housekeeping (particularily
    with respect to stopping the driver etc)
    #7     If a routine is running at DISPATCH_LEVEL you are limited to spin locks for synchronization. You can with a zero timeout check the status of a kernel dispatcher object.   In general, routines like this should be
    designed to only use spinlocks.
    #8    An arbitrary thread is just that, it may be a thread in any process. Basically a currently running thread is grabed and used to run the interrupt so that the scheduler which has overhead and is not designed to run at interrupt level
    IRQL's does not need to run.
    Don Burn Windows Filesystem and Driver Consulting Website: http://www.windrvr.com Blog: http://msmvps.com/blogs/WinDrvr

  • Some question on thread

    i think threads are unpredictable.say, the following code. some questions on the code.
    public class Rpcraven{
         public static void main(String argv[]){
         Pmcraven pm1 = new Pmcraven("One");
         pm1.run(); // line1
         Pmcraven pm2 = new Pmcraven("Two");
         pm2.run();  // line 2
    class Pmcraven extends Thread{
    private String sTname="";
    Pmcraven(String s){
         sTname = s;
    public void run(){
         for(int i =0; i < 2 ; i++){
              try{
               sleep(1000);
              }catch(InterruptedException e){}
              yield();
              System.out.println(sTname);
    }question 1 > note line 1 and line 2 . does this two threds are staarted at the same time ? or line 1 first and line 2 second as in the code ? this is very much important to me.
    question 2 > ok, whoever goes first , now lets come to the try-catch block . there is sleep() who will sleep first ? so i need to know which thread is going to sleep first ? bcoz then i can say who will get the yield() method.
    i find difficult to predict the output of this thred.
    Output of One One Two Two.
    one more thing, threads are always called by start() method ( run() is called implicitly) . here start() is not usued . still the code is working . how ?

    question 1 > note line 1 and line 2 . does this two
    threds are staarted at the same time ? or line 1 first
    and line 2 second as in the code ? this is very much
    important to me.If it's important, you are doing something wrong...
    First, you shouldn't call the threads' run() method, that doesn't "start" the thread, it just calls run(). Use start() instead.
    The threads are sort of started in order, but probably not in the way you think.
    Think of it like this: there is a list of threads in the JVM. start() puts the thread in the list. After that, the CPU of your computer can run any thread in the list, for as long as it feels like. The CPU might run thread 1 for a few instructions, then thread 2 for a while, or it might start with thread 2, ... If you have a multi-CPU machine, the threads are run at the same time. It's unpredictable, except when you do explicit synhcronization or waiting.
    question 2 > ok, whoever goes first , now lets come to
    the try-catch block . there is sleep() who will sleep
    first ? so i need to know which thread is going to
    sleep first ?This is unpredictable. You can't know it. It will vary from run to run.
    If you need two threads to do something in a predictable order, you'll need to do synchronization and waiting.
    one more thing, threads are always called by start()
    method ( run() is called implicitly) . here start()
    is not usued . still the code is working . how ?You are not starting the threads, you are calling their run() methods sequentially.

  • Question about EJB and thread safe coding - asking again!

    sorry everyone, no one seems to be interested in helping me on this, so i post it again.
    i have a question about the EJB and thread safe coding. when we build EJBs, do we need to worry about thread safe issue? i know that EJBs are single threaded, and the container manages the thread for us. maybe i am wrong about this. if i wasnot, how can we program the EJB so that two or more instance of EJB are not going to have deadlock problem when accessing data resources. do we need to put syncronization in ours beans, do we even need to worry about creating a thread safe EJB? thanks in advance. the question really bothers me a lot lately.

    sorry everyone, no one seems to be interested in
    helping me on this, so i post it again.Excellent plan. Why not search a little bit on your own instead of waiting for your personal forum slaves to answer your call. See below.
    i have a question about the EJB and thread safe
    coding. when we build EJBs, do we need to worry about
    thread safe issue? Read this: http://forum.java.sun.com/thread.jsp?forum=13&thread=562598&tstart=75&trange=15
    i know that EJBs are single
    threaded, and the container manages the thread for us.
    maybe i am wrong about this. if i wasnot, how can we
    program the EJB so that two or more instance of EJB
    are not going to have deadlock problem when accessing
    data resources. do we need to put syncronization in
    ours beans, do we even need to worry about creating a
    thread safe EJB? thanks in advance. the question
    really bothers me a lot lately.
    Java's Thread Tutorial
    JavaWorld: Introduction to Java threads
    IBM: Introduction to Java threads
    Google: java+threads+tutorial

  • General question about thread-safe program

    Obviously in multi-user application, especially web-based application, we will need to consider thread safety. However, modern web servers and DBMS are already threaded, so to what extent the application programmer are freed from this worrying, and in what situation we must consider thread-safe in our code?
    Thanks

    if you use a J2EE compliant application server and write custom business object as enterprise beans, all concurrent access is handled by the server. however, if you code accesses resources concurrently, you need to handle this yourself. e.g. if a business class write to a file and multiple instances of this class in multiplt threads are running, you need to handle the access of these resources in your code (e.g. keyword "synchronized" or custom locking mechanisms).

  • Question about singleton design

    Hi all
    i have a question about singleton design. as i understood it correctly, this pattern garantees us a single instance of a class at any time. in a environment of concurrent access(multiple user access at the same time) , does this single instance put a constraint on concurrency(singleton == synchronization)? i have developed a service object that reads in properties and constructs some other objects. the reason i made it singleton is that i only want this service object to load the properties once. and when it is called to create other objects, it always has one copy of the propertis. making this service singleton, will it limit the threads to access it and construct other objects? thanks for your help.

    If there's no write access to the HashMap, then
    you're thread safe.You were probably typing at the same time as the previous post, which explicitly says there IS write access to the HashMap.
    I don't know what it is, but people seem to have this magical view of concepts. Singleton is just what it is. It doesn't have a magical aura that causes other things to behave differently. A singleton is just Java code that can have thread safety problems just like any other Java code. So to the OP: forget about the fact that this is a singleton. That's irrelevant. Ask if a method needs to be synchronized.
    (And yes, a method that tests if a variable is null and assigns an object to it if it isn't null does need to be synchronized if it's going to have multiple threads accessing it.)

  • Thread safe ?

    Hi
    This code is currently running on my companys server in a java class implementing the singleton pattern:
    public static ShoppingAssistant getInstance() {
        if (instance == null) {
            synchronized (ShoppingAssistant.class) {
                instance = new ShoppingAssistant();
        return instance;
    }1 Is there really a need for synchronizing the method?
    2 If you choose to synchronize it. Why not just synchronize the whole method?
    3 Is this method really thread safe? Is I see it a thread A could be preempted after checking the instance and seing that it is null. Thereafter another thread B could get to run, also see that instance is null and go on and create the instance. Thereafter B modifies some of the instance�s instance variables. After that B is preempted and A gets to run. A, thinking instance is null, goes on and create a new instance of the class and assigns it to instance, thus owerwriting the old instance and creating a faulty state.
    By altering the code like this I think that problem is solved although the code will probably run slower. Is that correct?
    public static ShoppingAssistant getInstance() {
        synchronized (ShoppingAssistant.class) {
            if (instance == null) {
                instance = new ShoppingAssistant();
    }Regards, Mattias

    public class Singleton {
    private static final instance = newSingleton();
    public static Singleton getInstance() {
    return instance;
    }This seems like it's so obviously the standard
    solution, why do
    people keep trying to give lazy solutions? Do they
    expect it to be
    more efficient that this?I can see one possible performance gains with a lazy solution:
    If you use something else in that class (besides getInstance()), but don't use getInstance, then you don't take the performance hit of instantiating the thing.
    Of course, this is dubious at best because how often do you have other static methods in your singleton class? And not use the instance? And have construction be so expensive that a single unnecessary one has a noticeably detrimental impact on your app's performance?

  • Thread safe RMI

    Thread safe RMI.
    My RMI server provides clients with the ability to CRUD data but in order to manage concurrency I did the following.
    1stly I would like to understand correctly the issues of RMI server objects....
    It is my understanding that RMI server can cater for eg 100 clients by spawning 100 threads at random for each client. This process is not managed (thread wise) and the result is that 20 clients wishing to update record A can do so at will? Various steps can be taken from what I gather...
    a) Synchronise (expensive)
    b) implement a lock manager.
    The step I have taken is include a lock manager and I have ensured that all locking an unlocking occur in a singleton server object that manages all sensitive data CRUD operations. Now I use a lock manager but I would like to know what happens if for eg the 1st RMI client dies and has its thread blocking
    all other threads from locking the same record? Does the thread die with the client or is there a counter measure for this? The obvious answer that comes to mind is Object.wait() inside the lock manager?
    The reason I ask was that because all of the locking occurs in a single method call in the Network
    Server's JVM, so is there a need to worry about the RMI connection dying during the middle the locking operation.
    Edited by: Yucca on May 23, 2009 8:14 PM/*
    * @(#)LockManager.java
    * Version 1.0.0
    * 27/03/2009
    import java.util.HashMap;
    import java.util.Map;
    import java.util.logging.Logger;
    import java.util.ResourceBundle;
    class LockManager {
         * The <code>Map</code> containing all the record number keys of currently
         * locked records that pair with the cookie value assigned to them when they
         * are initially locked.
        private static Map<Integer, Long> currentlyLockedMap =
                new HashMap<Integer, Long>();
        private static final Logger LOG = Logger.getLogger("project.db");
         * Locks a record so that it can only be updated or deleted by this client.
         * Returned value is a <code>long</code> that is the cookie value that must
         * be used when the record is unlocked, updated, or deleted.
         * If the specified record is already locked by a different client, then the
         * current thread gives up the CPU and consumes no CPU cycles until the
         * record is unlocked.
         * @param   recNo                   the assigned primary key of the record
         *                                  to be locked for an operation.
         * @param   data                    a <code>Data</code> instance used to
         *                                  check if the record exists before
         *                                  attempting the lock operation.
         * @return                          A <code>long</code> containing the
         *                                  cookie value that must be used when the
         *                                  record is unlocked.
         * @throws  RecordNotFoundException if specified record does not exist or if
         *                                  specified record is marked as deleted
         *                                  in the database file.
        long lock(int recNo, DB data) throws RecordNotFoundException {
            LOG.entering(this.getClass().getName(), "lock", recNo);
            synchronized (currentlyLockedMap) {
                try {
                    while (currentlyLockedMap.containsKey(recNo)
                            && currentlyLockedMap.get(recNo)
                            != Thread.currentThread().getId()) {
                        currentlyLockedMap.wait();
                    // Check if record exists.
                    data.read(recNo);
                    long cookie = Thread.currentThread().getId();
                    currentlyLockedMap.put(recNo, cookie);
                    LOG.fine("Thread " + Thread.currentThread().getName()
                            + "got Lock for " + recNo);
                    LOG.fine("Locked record count = " + currentlyLockedMap.size());
                    LOG.exiting(this.getClass().getName(), "lock", true);
                    return cookie;
                } catch (InterruptedException ie) {
                    throw new SystemException("Unable to lock", ie);
         * Releases the lock on a record. The cookie must be the cookie returned
         * when the record was locked.
         * @param   recNo                   the assigned primary key of the record
         *                                  to be unlocked after an operation.
         * @param   cookie                  the cookie returned when the record was
         *                                  locked.
         * @throws  RecordNotFoundException if specified record does not exist or if
         *                                  specified record is marked as deleted
         *                                  in the database file.
         * @throws  SecurityException       if the record is locked with a cookie
         *                                  other than cookie.
        void unlock(int recNo, long cookie) throws RecordNotFoundException,
                SecurityException {
            LOG.entering(this.getClass().getName(), "unlock",
                    new Object[] { recNo, cookie });
            synchronized (currentlyLockedMap) {
                checkLock(recNo, cookie);
                currentlyLockedMap.remove(recNo);
                LOG.fine("released lock for " + recNo);
                currentlyLockedMap.notifyAll();
            LOG.exiting(this.getClass().getName(), "unlock");
         * Checks if the given record is locked before doing any modification or
         * unlocking for the record.
         * <p/>
         * Checks the <code>Map</code> of record number keys and cookie values
         * to see if it contains the given record number.
         * @param   recNo                   the assigned primary key of the record
         *                                  to be checked if it is locked.
         * @param   lockCookie              the cookie returned when the record was
         *                                  initially locked.
         * @throws  SecurityException       if no lock exists for the record or if
         *                                  the record has been locked with a
         *                                  different cookie.
        void checkLock(int recNo, long lockCookie) throws SecurityException {
            LOG.entering(this.getClass().getName(), "checkLock",
                    new Object[] { recNo, lockCookie });
            // Check if record has been locked
            if (!currentlyLockedMap.containsKey(recNo)) {
                throw new SecurityException(ResourceBundle.getBundle(
                        "resources.ErrorMessageBundle").getString(
                        "lockNotAppliedKey"));
            // Check if record has been locked by different cookie.
            if (currentlyLockedMap.get(recNo) != lockCookie) {
                throw new SecurityException(ResourceBundle.getBundle(
                        "resources.ErrorMessageBundle").getString(
                        "notLockOwnerKey"));
            LOG.exiting(this.getClass().getName(), "checkLock");
    }Edited by: Yucca on May 23, 2009 8:16 PM
    Edited by: Yucca on May 23, 2009 8:18 PM

    It is my understanding that RMI server can cater for eg 100 clients by spawning 100 threads at random for each client.No. It spawns a new thread for every new connection. At the client end, RMI makes a new connection for every call unless it can find an idle connection to the same host that is less than 15 seconds old. So if the client is doing concurrent calls there will be concurrent threads at the server for that client.
    This process is not managed (thread wise)'Managed' meaning what?
    the result is that 20 clients wishing to update record A can do so at will?The result is that an RMI server is not thread safe unless you make it so.
    a) Synchronise (expensive)Compared to a database update the cost of synchronization is trivial.
    b) implement a lock manager. The database should already have one of those, and so does java.util.concurrent. Don't write your own. Personally I would just syncrhonize around the database calls.
    what happens if for eg the 1st RMI client dies and has its thread(a) the client doesn't have a thread, see above. The call has a thread.
    (b) at the server, the call will execute, regardless of the state of the client, until it is time to write the result back to the client, at which point the write will encounter an IOException of some description and the thread will exit.
    blocking all other threads from locking the same record?That can't happen unless you foul up your concurrency management.
    Does the thread die with the clientIt dies with the call.
    is there a need to worry about the RMI connection dying during the middle the locking operation.The server JVM won't notice until it is time to write the call result back, see above.

  • Thread safe logging class, using final and static

    Hi,
    I'm looking through a logging class (which writes entries to a text file and so on) written by someone else, and I'm trying to determine whether it's thread-safe...
    Essentially the class looks like this:
    public final class Logger {
    private static FileOutputStream fout;
    private static PrinterWriter pout;
    private static final long MaxLength = 100000;
    static {
    /* basically checks size of logfile, if bigger than 100k, then copy it as bak, and start again */
    public void write(String msg) {
    /* write entry into log file */
    public void writeWithTimeStamp(string msg) {
    /* write entry with time stamp into log file */
    Now, I could be wrong, but I don't think that the class is thread-safe is it? in order to be thread-safe, I would have to use synchronized before write() and writeWithTimeStamp(), right?
    My confusion arises from the use of the keyword "final" at the top of the class. This class isn't being inherited (or rather, there's no reason for the class not to be inheritable)... so what is it's purpose, if there is one?!
    And my other question concerns the static block. But I need to describe the current setup first: The Logger class is being use by a file server. File server basically sits there, accepts socket connections from the outside, and takes text files and output them into a local directory. When a new socket connection is created, a new thread is created. As it stands right now, each thread instantiates its own Logger object which seems weird! Bringing me to my question which was, if each thread instantiates its own Logger object, the static block is only ran ONCE, regardless of how many threads (and therefore Logger objects) are created, right??
    And wouldn't it be a better idea to simply create only ONE Logger object and pass it by reference to all newly created threads as they are needed so that all threads access the same and only Logger object? (and therefore utilize sychronization)
    Thanks!

    In JDK 1.4, there are already classes written that do all of that work. Check out the docs for the java.util.logging package. Specifically, check out FileHandler (which can rotate log files if they are greater than a specified size) and LogRecord (which is a standardized way to store logging entries). I believe the class is threadsafe, it doesn't say it isn't. Try it and see. If not, you can easily make a threadsafe wrapper for it (or any class for that matter).
    The online documentation is at:
    http://java.sun.com/j2se/1.4/docs/api/index.html
    If you are curious, the simplest way to make any class threadsafe, if you don't want to or are not able to modify the class code itself is to define another class that calls methods of the original class, but that is synchronized.
    Example:
        // NonThreadSafe.java
        public class NonThreadSafe {
            public NonThreadSafe (String s) {
                // Constructor
            public void SomeMethod (int param) {
                // Do some important stuff here...
            public int AnotherMethod (boolean param) {
                // Do some more important stuff here...
        // ThreadSafeWrapper.java
        public class ThreadSafeWrapper {
            protected NonThreadSafe nts;
            public ThreadSafeWrapper (String s) {
                nts = new NonThreadSafe(s);
            public synchronized void SomeMethod (int param) {
                nts.SomeMethod(param);
            public synchronized int AnotherMethod (boolean param) {
                return nts.AnotherMethod(param);
            public NonThreadSafe GetNonThreadSafe () {
                return nts;
        };Unfortunately, ThreadSafeWrapper isn't derived from NonThreadSafe, so you are somewhat limited in what you can do with it compared to what you could do with NonThreadSafe. AFAIK, you can't override unsynchronized methods with synchronized ones.
    Another thing you could do is just write a method that writes to your logging class, and synchronize just that method. For example:
        // ThreadSafeLogger.java
        public class ThreadSafeLogger {
            public static synchronized void LogMessage (MyLogger log, String msg) {
                log.writeString(msg);
        // In another thread, far, far away:
            ThreadSafeLogger.LogMessage(theLog, "Blah");
            ...Hope that helps.
    Jason Cipriani
    [email protected]
    [email protected]

  • Is the java 1.5 default SAXParser thread safe.

    I used the following code to create a parser and validate my xml data.
    But the following code is causing too many open file issue.
    After doing some analysis I understood that each object of parser is open the file "file://var/app/bea/files/wfinf/xmlschema/WorkflowDecisionResponse.xsd".
    So if I comment the setProperty method it will work fine.
    My question is this parser is thread safe so that I can create single instance of parser and can be shared by all my thread?
    If not can some body suggest a better idea to validate it.
    public static boolean validate(String XMLData){
         SAXParserFactory factory = SAXParserFactory.newInstance();
         factory.setNamespaceAware(true);
         factory.setValidating(true);
         SAXParser parser = factory.newSAXParser();
         parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
         parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "file://var/app/bea/files/wfinf/xmlschema/WorkflowDecisionResponse.xsd");
           try{
              parser.parse(new InputSource(new StringReader(XMLData)), new DummyHandlerImpl());
           }catch(Exception e) {
               return false;
           return true;
    }

    Hi There,
    I found this thread of yours with no reply from anybody.
    I'm also facing a similar issue. Did you found a solution to this.
    If yes please share.
    Regards,
    Mayank

  • HTTP request/response object not thread safe.

    According to the serlvet spec. Http Request/Response
    are not thread safe. Quoting from the Spec:
    " Implementations of the request and response objects are not guaranteed to be thread safe. This means that they should only be used within the scope of the request handling thread. References to the request and response objects must not be given to objects executing in other threads as the resulting behavior may be nondeterministic."
    This has prompt me to ask the following question.
    For Example I have a servlet which does the following
    request.setAttribute("myVar","Hello");
    The request and response is dispatched(using RequestDispatch.include(request,response)) to another
    servlet which retrieve this attribute i.e request.getAttribute("myVar");
    Is this safe?
    The Spec only said "The Container Provider must ensure that the dispatch of the request to a target
    servlet occurs in the same thread of the same VM as the original request." I take this meaning that the targeting servlet does not have to run in the same thread(only dispatch), otherwise it would be safe.

    To put it another way, you can only have onle thing working on a request at a time. For instance, the ServletContext is available to all servlets running on a server. If you tried to save a particular request to the ServletContext, it would potentially be available to many concurrently running servlets. They could all change whatever in it at the same time. Each servlet is in its own running thread. Hope that helps some.

Maybe you are looking for