Is static method in JAVA creates a single instance?

不羁的心 提交于 2019-12-08 05:07:39

问题


I have a doubt.
Suppose in a multithreaded environment 10K users are using a site simultaniously and the site has a static method.
If a static method in JAVA creates a single instance, then the 10k-th user needs to wait for the method until rest of the users complete their usage.
Am I right?
Can anybody please explain?


回答1:


If a static method in JAVA create a single instance, then 10K th user need to wait for the method untill rest of the usres complete there usage.

Calling a static method doesn't create an instance implicitly. You can do so within the method, of course - but you don't have to.

Nor does creating an instance require a lock - although again, you can add synchronization should you wish to.

So in the case of a simple static method which doesn't need any synchronized access to shared data, there should be no problem with multiple threads calling that method concurrently.




回答2:


I guess you mean something like a singleton or a factory, e.g.

public class X {

    public static X getInstance() {
        return new X();
    }

    private X() {}
}

Then it all depends on what you do on the static method. If the method does not care about threading (as in the example above), then it should not be synchronized and can be executed concurrently, and then you're wrong since it is OK to execute X.getInstance() concurrently and 10Kth won't have to wait for previous to finish.

If the method cannot be multi-threaded, it should be synchronized (either the whole method or a part of it) then yes, you're right.




回答3:


NO..10K th user no need to wait for the method untill rest of the usres complete there usage.

Because it's not static method is not synchronized... so multiple thread can acess same object.



来源:https://stackoverflow.com/questions/15339059/is-static-method-in-java-creates-a-single-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!