I have a singleton class:
public class Singleton {
private static Singleton istance = null;
private Singleton() {}
public synchronized static Singleton getSingleton() {
if (istance == null)
istance = new Singleton();
return istance;
}
public void work(){
for(int i=0; i<10000; i++){
Log.d("-----------", ""+i);
}
}
}
And multiple Threads are calling the work() function:
public class Main {
public static void main(String[] args) {
new Thread (new Runnable(){
public void run(){
Singleton s = Singleton.getSingleton();
s.work();}
}).start();
System.out.println("main thread");
new Thread(new Runnable() {
public void run() {
Singleton s = Singleton.getSingleton();
s.work();
}
}).start();
}
}
I noticed the two Threads are running concurrently, as if two work functions were instantiated at the same time.
I want the last thread to be run in place of the previous thread, rather then concurrently. Is it possible in java to make the second call override the memory space of the first call?
getSingleton()
method should besynchronized
– Geometricwork()
should not be static, otherwise the example doesn't make sense – Unconcernedsynchronized
won't stop two threads from running concurrently: it will only serialize their access to thegetSingleton()
function. Put otherwise, it means that you can be sure that no matter how many threads are currently in execution, only one of them at most will be executinggetSingleton()
at any point in time. – Unconcerneds.work()
because you're invoking a static method using an instanced class: at the very least you should be callingSingleton.work()
. – Unconcerned