Static methods in multi-threaded environment

Hi,
I am wondering what happens when several threads try to access the same static method ?
The static method is not synchronized.
Will this create any performance issues ?
The actual scenario is of a J2EE server, where several Session Bean instances try to access a static method in a utility class. Will some session beans have to wait till others are being serviced ?
thnx n regards
s giri

thanx for replying.
yes. the operations are thread-safe. we do not change the state of any object.
but we make an rmi call to another application thru this static method.
is it ok?
Currently, my session bean has too many private methods - each calling the other application. Due to some quality metrics (a class must be restricted to 700 lines) we have to consider moving these private methods into some Helper class in the form of "public static methods". We have made many utility methods as static, but have some reservations abt doing a similar thing for these methods that call other application.
regards
Shivraman

Similar Messages

  • Static methods in multi-thread environment.

    Sorry for this silly question, but I have no clue...
    If you're using classes with static methods in a application server environment, would that imply all threads use that same 'one in the jvm' method and would there be a possibility for performance loss?
    Is calling another static method from a static method a good idea in a multi-thread environment, with respect to performance? Somehow I seem to get this java.lang.NoClassDefFoundError. Any ideas? The classes are in the same package. I only get these kind of problems calling static methods from static methods in a multi-thread environmnent. The static methods are pure utility functions and of course do not use class state.
    Thanks for your help.

    Sorry for this question, wasn't thinking straight. I have the answer, won't post question on multiple forums.

  • Are static methods in Java thread safe?

    Are static methods in Java thread safe?
    thanks,
    suresh

    if static method use the instance variable
    You mean member variable, where member variables are either class variables (static) or instance variables (non-static).
    then you have to make it thread safe using
    synchronization Not necessarily. Depends on requirements and usage context.
    else in case of local var. it
    is thread safe. Not necessarily. That local variable could refer to an object that's visible to multiple threads.
    Statements like "Local variables are threadsafe but member variables aren't" are an oversimplification.
    Something is threadsafe if it cannot be made to behave incorrectly simply by running it in a multithreaded context. Determining that can be very difficult.

  • Help on calling static method in a multithreaded environment

    Hi,
    I have a basic question.. pls help and it is urgent.. plss
    I have a class with a static method which does nothing other than just writing the message passed to a file. Now i have to call this static method from many threads..
    What actually happens ???
    Does all the thread start to execute the static method or one method executes while the other threads wait for the current thread to complete execution?. I am not talking about synchronizing the threads...my question is what happens when multiple threads call a static method??
    Pls reply.. I need to design my project accordingly..
    Thanks
    Rajeev

    HI Omar,
    My doubt is just this..
    I wanted to know what might happen if two threads try to access a static method.. Logically only one thread can use the method since it is only only copy... but i was wondering what might happens if f threads try to access the same static method.. My Situation is this.. I have a cache which is just a hash table which will be only one copy for the whole application.. No when i get a request I have to check if the id is avaible in the cache. if it is available i call method 1 if not i call method2. Now Ideally the cache should be a static object and the method to check the id in the cache will be a normal instance method..
    I was just wondering what might happen if i make the method static.. If i can make it static i can can save a lot of space by not creating the object each time.. u know what i mean.. That y i wanted to know what happens..
    Rajeev

  • Multiple Containers read/write access in multi-threaded environment

    I'm been reading the Berkeley DB XML Transaction Processing document and have a few questions. I have a multi-threaded environment (not multi-process).
    1) In the "Summary and Examples" section, there is an example of several worker threads that perform many writes to a shared container. The one container is passed to all the worker threads, rather them having their own instance of the container. In my application, I could potentially have multiple worker threads acting on the same container, is it better to provide some type of connection pool, so each thread has access to the same container? Is their a problem with each thread creating a new instance of the container and writing to that? Is their pros and cons to each approach?
    2) In some specific web applications, they only require read-access and have no intention of writing to the database. If the environment was created with transactions, can these applications open the environment in read-only mode, so as to not suffer the performance penalty of using transactions? Or do they still require transaction support since other threads in other applications might be writing to it. Is it better in this case to
    3) Is there any decent connection pooling framework that work well with BDB XML? If transactions are involved, it seems pretty important to always close the container once you are finished with it, which kind of defeats the purpose of pooling. I see a container somewhat analogous to a JDBC transaction, where in connection pooling these transactions remain open, but in BDB XML, it doesn't seem like this is good practice. So clarification here would be appreciated.
    Thanks in advance...
    Chris

    Chris,
    I'd be careful about trying to draw too many analogies with other sorts of systems. In many ways BDB XML is simpler -- it's just a library, no server process.
    An open container is analogous to an open file handle/descriptor in your operating system. It can safely be shared by all threads within a given process. In fact, you should not create more than one -- while that works, it can just be confusing, and a source of errors (for example, if you use a different path to open the container each time, you'll have problems). So by all means share them. Most Java applications just point them in a class that is accessible to all threads.
    Other objects that can, and should be shared among threads include:
    Environment
    XmlManager
    XmlQueryExpression
    Most others should not. You also mention closing your containers -- there is no reason to close your active container objects until your application needs to shut down. A long-running application will want to use db_checkpoint (or equivalent) to ensure that modified pages are flushed from the transaction log to the database files, but that's about it.
    As for concurrency, you obviously need transactions for concurrent write operations. If you want concurrent read access to the same containers, they should use transactions as well. Even if you don't explicitly use transactions, locks are always taken on pages in transactional containers. You cannot open the same container transactionally and not transactionally at the same time -- bad things could happen.
    Depending on your performance needs, you could using snapshot concurrency, and see how it works for you. While locking does incur some overhead, it may be acceptable.
    You mention creating your own "snapshot" of a container and running read-only on that copy. That's possible to do, but you have to be careful of how you create the snapshot (following hot backup procedures). Also, if you intend to open that "new" container in the same environment or application as the old one, you need to run a program on it to change its internal identification so Berkeley DB won't think it's the same file. That is, you can't just copy a container file to a new name and just open it like it's a new container if it's still in the vicinity of the original. See the -r option for the db_load program.
    Now that you are probably really confused, good luck!
    Regards,
    George

  • Memory leak with multi-threaded environment

    When starting an environment with the THREADED_MUTEXED
    or THREADED_UNMUTEXED mode parameter, the oracle OCCI API
    has a memory leak. This can be demonstrated by modifying
    the "occidml.cpp" demo program as follows:
    Replace line 26:
    env = Environment::createEnvironment (Environment::DEFAULT);
    with
    env = Environment::createEnvironment (Environment::THREADED_MUTEXED);
    And replace line 164:
    demo->displayAllRows();
    with
    for (int ii=0; ii<10000; ii++) demo->displayAllRows();
    Recompile and run the program, and use "top" to see the
    size of the process's used memory continually increase
    unbounded.
    I am using the Oracle 9.2.0.1.0 database on Linux,
    gcc version 2.96.
    Is anyone aware of a fix for this problem?

    Yeah, I did suffer from this.
    If possible , you can switch to using OCCI on Oracle 10G client , you will find no memory leak issue anymore.
    Another issue is that OCCI is using default connection-blocking implementation , if a DB connection is blocked by accident just like plugging out the network link, you can not get any timeout or connection closed indications. You must implement your own OCCI connection timeout strategy, and you must kill the thread/process you are using.

  • Using iTunes SDK in multi thread environment

    I'd like to use the Windows iTunes COM SDK in a multithread manor.
    Ex. create the iTunes COM object in thread A and use it again in thread B.
    How it the COM interface for iTunes defined (MULTITHREADED, APPERTMENT THREAD, SINGLETHREADED)
    Can I then marshall the interface, between interfaces, without deadlocking my app? (I hate frozen apps, so I use threads as much as possible).

    Annoyingly the SDK hasn't been updated in over three years. I've had a casual look via Visual Studio's object inspector to see if I can spot any new methods or properties that could be useful but if they are there then they are hidden well. Media Kind, for example, was introduced in iTunes 9, I think, but can't be read from code.
    I don't know what tasks you're hoping to automate, but you might find some of my scripts useful either in their own right or as food for thought.
    tt2

  • Problem about Sparc/solaris10 signal in multi-thread environment

    Normally if we send a signal to a process which has several threads, the main thread of this process will handle this signal. But I found in some cases an other thread (not main thread) handled signals even if main thread was alive(mostly main thread was being blocked by __pollsys()).
    I want to know why and how this happens.
    Thanks.

    according to man signal.h from a solaris 10 machine ...
    Asynchronously generated signals are not directed to
    a particular thread but are handled by an arbitrary thread
    that meets either of the following conditions:
    .... a list of conditions.
    So if you have threads that you don't want to take signals, then those threads
    must block that signal eg pthread_sigmask()
    it is just chance that it usually goes to your "main" thread.
    tim

  • Static method and threads?

    I have a question regarding "static". for example, I have the following code
    class Test{
    public int i=0;
    public static calculateInt(){
    ....some operations on i;
    if two processes attempt to call Test.calculateInt() at the same time. What will the effects be? shall these two calls be implemented totally independent? each call holds it own "i" for calculation. OR there will be operation conflicit on i.
    what if I change "public i" to :private i", the same effects?

    You can't operate on i in a static method, since i is an instance variable.
    If you make i static, then you can operate on it in a static method. In that case, all threads will share a single i--there's only one i for the whole class, and threads don't change that. Making it private won't change that.
    If you make the method into an instance (non-static) method, then any threads operating on the same instance will share the same i, regardless of whether it's public or private. Different threads operating on different instances will each have their own i.
    Java's Thread Tutorial
    JavaWorld: Introduction to Java threads
    IBM: Introduction to Java threads
    Google: java+threads+tutorial
    Also check out http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadLocal.html

  • Static Methods with all Final Parameters

    Gurus,
    I know the synchronization and static method question has been hashed out ad infinitum here. However, I was thinking of a slight twist. (Did a search but could not find something related to this. If this has already been posted, my apologies).
    Suppose you have a static method in which all of the parameters in the method signature are declared final. Let's assume also that you are not performing an operation with a high latency (say, database or network operations).
    Would it be "safe" to leave the static method unsynchronized in a multi-threaded environment? Would the final keyword(s) ensure that, throughout method execution, there is no longer a race condition?
    Would there be a difference between a primitive:
    static final public void doSomething(final int param) {}
    And an object that has mutator methods:
    static final public void doSomething(final List param) {}
    Basically, not having a formal CS background, I'm not sure how static methods are actually invoked on a low-level. It probably varies across JVM's, and maybe this question doesn't make much sense. However, I thought I would throw this out to see if anyone had implemented something similar.
    I might be giving "final" too much credit., but what would actually happen in a multi-threaded environment?
    Thanks much!
    - Saish
    "My karma ran over your dogma." - Anon

    I know the synchronization and static method question
    has been hashed out ad infinitum here. What question's that then?
    Suppose you have a static method in which all of the
    parameters in the method signature are declared final.
    Let's assume also that you are not performing an
    operation with a high latency (say, database or
    network operations).
    Would it be "safe" to leave the static method
    unsynchronized in a multi-threaded environment?Whether or not the parameters are final makes no difference - method parameters are local to the method and so are only visible to the current thread anyway. So making them final will have no effect on anything goning on in any other thread.
    Whether or not you are performing operations has no effect on whether or not you can call a method thread-safe. It might mean there is less contention and it might make race conditions less likely, but it won't eliminate them.
    So the answer is: If your would be thread safe with non-final parameters, then it will still be thread-safe when the parameters are all final. If it is not thread-safe with non-final parameters, then it will still not be thread safe with final parameters.
    Would the final keyword(s) ensure that, throughout
    t method execution, there is no longer a race
    condition?No. Absoloutely not.

  • Interesting Qtion: Synchronize a static method

    I know that a non-static method and a block can be synchronized.
    Can anyone tell me as to what it means to synchronize a static method of a class and how/when is it used. I just tried compiling the code and it gives no compiler/syntactical errors.
    it would be helpful if u could take up a simple class example.
    Thanks,
    Novice

    Hi,
    A good example for using synchronized static methods is the singleton pattern. E.g.
    public class Singleton
      private Singleton() {}
      private static Singleton fgUniqueInstance;
      public static synchronized Singleton getInstance()
        if (fgUniqueInstance==null) {
          fgUniqueInstance = new Singleton();
        return fgUniqueInstance;
    }If you won't synchronize this class in a multi-threading environment, it could happen, that more than one instance is created.
    Andre

  • Question using Java API in a multi threaded application for MDX queries

    Currently I’m building a web application that makes a lot of MDX calls using the Essbase Java API. Each time we run an MDX call we basically run the following code:
    IEssbase ess = IEssbase.Home.create(IEssbase.JAPI_VERSION);
    IEssDomain dom = ess.signOn(userName, password, false, null, "embedded");
    IEssCubeView cv = cv=dom.openCubeView("view", hostName, appName, cubeName);
    IEssOpMdxQuery op = cv.createIEssOpMdxQuery();
    op.setQuery(false,mdx,false,IEssOpMdxQuery.EEssMemberIdentifierType.NAME);
    cv.performOperation(op);
    IEssMdDataSet mddata = cv.getMdDataSet();
    cv.close();
    My questions is, is this the correct way to use the API in multi threaded environment where many users may be hitting the application at the same time? For every request do I need to create a separate IEssbase object and sign on to an IEssDomain? Or can I use a single IEssbase and IEssDomain object for the entire application? If not should I call the IEssDomain.signOff() method after each user’s request has completed? Which of the above objects are thread safe? I’m using Essabae 9.3.1. Any insight would be really appreciated.
    Thanks
    David

    Thanks for the input friend,
    I should have mentioned that in my application all
    connections to Essbase use the same user name and
    password so the filtering isn’t a concern. This is my
    first Java application using Essbase has a data
    source, I’m used to connecting to various SQL
    databases and I always use a connection pool, how is
    connection pooling handled in the Essbase java API?I'm not sure what happened to it since I never used it, but there used to be something called the High Availability Services or something that was essentially a connection pool for Essbase JAPI connections, but it required an extra license.
    Since you don't care about identity (everyone has full access to everything), you can create your own connection pool, but you'll have to manage your multithreading yourself. Its been this way since the beginning. The C API isn't/wasn't thread-safe either (we tried).

  • Need some explanations regarding static Method

    Hello,
    I have a code where a class has a static method access by other classes. This not working as I thought and I would like to understand why.
    Here below is the code.
    Here is a class having the static method "test"
    package test;
    public class StaticTest {
        public StaticTest() {
        public static void test (int i){
        while (i < 1000){
            System.out.println("i = " + i );
            i++;
    }Here is the code of another class (Thread) using this static method. This Thread can be initialized with an integrer value that will be passed to the static Method.
    package test;
    public class ThreadTester extends Thread {
        int x;
        public ThreadTester(int i) {
            x=i;
        public void run(){
            StaticTest.test(x);
    }Here is the code starting 2 Thread running in parallel and both are then calling the static method.
    //start 2 thread accessing the static method.
          ThreadTester test1 = new ThreadTester(0);
          ThreadTester test2 = new ThreadTester(200);
          test1.start();
          test2.start();
    ...As the second thread is started with a bigger value I thought that we would only have seen few printouts from the first thread starting by 0 and then printouts starting by 200.
    Here is what I thought regarding the result:
    i = 0
    i = 1
    i = 2
    i = 3
    i = 200 --> startup of the second thread, x in static method is overriden (at least this is what I thought!)
    i = 201
    i = 202
    i = 203
    i = 204
    i = 205
    i = 206
    i = 207
    i = 208
    i = 209
    But the real result is:
    i = 0
    i = 1
    i = 2
    i = 3
    i = 4
    i = 5
    i = 200
    i = 6
    i = 201
    i = 202
    i = 203
    i = 204
    i = 205
    i = 206
    i = 7
    i = 207
    i = 208
    i = 209
    i = 8
    It seems that there is 2 instances running in parallel. I thought that it would'nt be the case with the word "Static".
    Also I don't understand the result because if I use JBuilder in Optimizer mode I can see that there is only one instance of StaticTest object.
    Can anyone here explain me how is that possible?
    Thanks in advance for your help.
    Regards,
    Alain.

    >
    thread test1 creates its own stack and starts incrementing �i� starting at values 0. However, in the middle of incrementing, it gets kicked out by the OS (or JVM) into a �blocked� state to allow other threads to run. BUT before leaving the running state, test1 saves the stack state including the value of �i�.
    >
    Ok, now I understand, but then I have another question.
    What is the difference between the code shown in my first post and the following where we create 2 instances of StaticTest class (which is not static in this case for sure).
    How to decide (while coding) if it is better to use difference instances of class or not?
    package test;
    public class StaticTest {
        public StaticTest() {
        public void test (int i){ //Not static anymore
        while (i < 1000){
            System.out.println("i = " + i );
            i++;
    }We create new instance in the Thread.
    package test;
    public class ThreadTester extends Thread {
        int x;
        public ThreadTester(int i) {
            x=i;
        public void run(){
    StaticTest newInstance = new StaticTest(); //Create a new instance
            newInstance .test(x);
    }Alain

  • How are static methods handled in a multithreaded application?

    hi
    i have a class Drawer with a static method public static draw(Graphics g). now assume there are more thrads callin at the same time Drawer.draw(g). What happens? have some threads to wait until the others have finished calling the method, or can static methods be multithreaded, (can they perform simultaniously)?
    thanks, jo

    ups, i am not drawing on the screen, but in every thread i am drawing a Image. this means before i call the static method in every thread there will be created a BufferedImage and then i pass the Graphics from this images to the static method. also in this case the method performs simultaniously? every thread has its own image and graphics, so the static method should be perform at the same time, isn't it?

  • JMS multi thread best practise

    Hi,
    I would like to code a JMS layer that could be accessed by
    a multi thread environment (a web app)
    Is there any "Connection-Pool/DAO" equivalent design
    pattern for JMS ?
    Form what I know, connection are Thread Safe and Sessions
    are not ...
    Philippe

    Many J2EE providers have their own JMS facades which provide pooling - so you could just use your container's JMS wrappers.
    Another option, if you are inside a Servlet Engine, is to use Jencks which provides JMS & JDBC connection pooling as well as pooling of threads & message listeners & exception handling when consuming JMS messages.
    e.g. here's inbound message consumption...
    http://jencks.org/Message+Driven+POJOs
    and here's outbound JMS (i.e. pooling when sending JMS messages etc)
    http://jencks.org/Outbound+JMS
    Jencks is basically a Spring based JCA container so it takes care of all the pooling for you as well as handling message inflow & outflow and can work with XA if you need it as well as local transactions.
    James
    http://logicblaze.com/

Maybe you are looking for