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?
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.
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.
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