I came across a deadlock scenario which can be summarized as the StaticDeadlock class shown below.
This simple program will freeze at o.getClass(). Here's my speculation of what happened, but can someone explain it better?
1) the program enters StaticDeadlock static block
2) thread starts
3) main thread is put in wait for thread to finish, hence can't finish the static block
4) inside thread it access StaticDeadlock.o but StaticDeadlock's static block is not finished yet. Hence the program freezes?
public class StaticDeadlock
{
private static final Object o = new Object();
static {
MyThread thread = new MyThread();
thread.start();
try {
thread.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main (String[] args)
{
System.out.println("all is well.");
}
static class MyThread extends Thread
{
#Override
public void run ()
{
System.out.println("inside mythread");
o.getClass();
}
}
}
Yes, that's pretty much it. The new thread is waiting for the class initializer of StaticDeadlock to complete before it accesses the static member. See section 12.4.2 of the Java Language Specification for more details, in particular these steps:
Synchronize (§14.19) on the Class object that represents the class or interface to be initialized. This involves waiting until the current thread can obtain the lock for that object (§17.1).
If initialization is in progress for the class or interface by some other thread, then wait on this Class object (which temporarily releases the lock). When the current thread awakens from the wait, repeat this step.
If initialization is in progress for the class or interface by the current thread, then this must be a recursive request for initialization. Release the lock on the Class object and complete normally.
If the class or interface has already been initialized, then no further action is required. Release the lock on the Class object and complete normally.
It won't even get past step 1 in the second thread, as the first thread has the lock and won't release it.
Note that it's not calling getClass() which causes the problem - doing anything which requires the value of o will make the second thread wait until the class initializer has completed, which of course won't happen because the first thread is waiting for the second thread to finish.
Related
class Common
{
public synchronized void synchronizedMethod1()
{
System.out.println("synchronized Method1 called");
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("synchronized Method1 done");
}
public synchronized void synchronizedMethod2()
{
System.out.println("synchronized Method2 called");
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("synchronized Method2 done");
}
}
In the above class I have two synchronized methods which I am calling from run method of another class. Other class code is given below:
public class ThreadClass implements Runnable
{
private int id = 0;
private Common common;
public ThreadClass(int no, Common object)
{
common = object;
id = no;
}
public void run()
{
System.out.println("Running Thread " + Thread.currentThread().getName());
try
{
if (id == 11)
{
common.synchronizedMethod1();
}
else
{
common.synchronizedMethod2();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
Common c = new Common();
ThreadClass tc = new ThreadClass(11, c);
ThreadClass tc1 = new ThreadClass(20, c);
Thread t1 = new Thread(tc, "Thread 1");
Thread t2 = new Thread(tc1, "Thread 2");
t1.start();
t2.start();
}
}
From main method I am starting two different threads. In run method I have given a condition to send both different threads to different synchronized methods. Output produced by the code is:
Running Thread Thread 2
Running Thread Thread 1
synchronized Method2 called
synchronized Method2 done
synchronized Method1 called
synchronized Method1 done
MY QUESTION FOR THE OUTPUT IS:
When thread 2 goes to synchronized Method2 it prints 3rd line of output and goes to sleep for 1 second. Now since thread 1 is not blocked by anything so it should execute and print 5th line of the output just after 3rd line of output and should go to sleep then but this is not happening instead when thread 2 goes to sleep it make's thread 1 also sleep then first thread 2 complete's its execution after which thread 1 completes its execution.
Such a behavior is not happening if I remove synchronized keyword from methods.
Can you please explain me the reason behind different way of processing the code with and without synchronized keywords.
Thanks in advance.
Such a behavior is not happening if I remove synchronized keyword from methods. Can you please explain me the reason behind different way of processing the code with and without synchronized keywords.
This is actually the entire purpose of the synchronized keyword. When you have several synchronized instance methods of the same class, only one may be executing at a time. You have written this:
class Common {
public synchronized void synchronizedMethod1(){}
public synchronized void synchronizedMethod2(){}
}
Because both methods are synchronized, only one may be executed at once. One of them can't start the other one is done.
How does this work? In short, you have a Common object and call a synchronized instance method of it. When you call synchronzedMethod1, that method will "lock" the Common object (called "acquiring the lock"). While that method has that lock on that Common object, if you try to call any other synchronized method on that same object, it will try to lock it and it will find that it's already locked. So any other attempt to lock the object will hang until they can do so. Once synchronizedMethod1 finishes, it will unlock the Common object (called "releasing the lock") and anybody can then try to lock it, such as synchronzedMethod2.
So in short, synchronized specifically makes it so you can't have two synchronized methods of the same class happening at once. This is useful because some problematic behavior can come from not doing this. As an example, ArrayList does not do this, so if one thread tries to add an object to an ArrayList while another tries to iterate over it, it might throw a ConcurrentModificationException and make everyone sad.
A sleeping thread does not release its locks, but you can replace your sleep(...) calls with wait(...). Keep in mind, though, that only the lock of the object having wait(...) called on it will be released, so you'd have to devise a different solution if you expected multiple locks to be released while waiting.
synchronising a method doesnt mean just the method itself synchronised
synchronized void x(){}
equals to:
void x(){
synchronised(this){}
}
Since both thread access same Common instance first thread will get the ownership of the Common object lock doesnt matter which synchronised method called and it will just release this lock after this method body completed its job.
If you would send two Common instance there would not be a problem since they are not static. Also you might be interested in ReentrantLock
First of all synchronized keyword is used to define mutual exclusion. Here mutual exclusion achieved by Monitor concept. One more thing is sleep does not release monitor. It just pause the execution of current thread for some time. Other threads which requires the monitor have to wait until the thread which acquired monitor release it.
There is two ways to use synchronized...
First one is using synchronized blocks.
synchronized(obj){...}
Here if any thread want to enter into synchronized block it have to get monitor of obj.
Second one is to using synchronized method.
synchronized void meth(){...}
Main difference between synchronised method & block is synchronised method use monitor of object it self & synchronised block can have monitor of any object.
Synchronized method can be defined using synchronized block as follows...
void meth(){
synchronized (this){
//method body
}
}
Now you can use the synchronised block to prevent the problem of blocking another method. Here you have to define synchronised block on different objects so both methods can execute concurrently but multiple threads can not execute same method concurrently.
I have an application with 2 threads (the main and another thread t1) which share a volatile variable myVar. Any ideas on how to make the main thread to call a method myMethod by signaling in some way from t1 ?
I implemented it by using ChangeListener and myMethod is called when myVar changes, BUT the method is called from t1, and not from the main thread (note: I need to call this method from the main thread because this is a call to a JavaScript code from Java, so for a security reason only the main thread can do so). Thanks in advance.
You would have to have your main thread spin in a loop on some scalar, I would recommend one of the Atomics that java provides (http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/package-summary.html), but you could use volatile if you wanted for this I think.
Each thread can only run sequentially - it's just the way computing works. The way you will handle this, is when the main thread spins in some sort of loop, you eventually check to see if this scalar of yours has been set, and when it has, you want unset the variable and execute your JavaScript. In this particular piece of your code, I think the Atomics have an advantage over the volatile with the use of the compareAndSet operations because using volatile can mess you up a bit between threads if you are trying to check the value in one operation and then set it again in another operation which gives the other thread enough time to set it again - meaning you may miss a call to your JS because the other thread set the variable between the main thread checking it and setting it (although the use of volatile vs Atomics may be interpreted as my opinion).
//main thread
AtomicBoolean foo = new AtomicBoolean(false);
while (...somecondition...){
if(foo.compareAndSet(true, false)){
//execute JS
}
//do some other work
}
and in your T1 thread, just call foo.set(true).
If you expect main to call your JS for each time T1 sets foo to true, then you will have to block in T1 until main has unset foo, or use an AtomicInteger to count how many times T1 has set foo - depending on your needs.
Since both tread sharing the same instance of myVar, you can make both thread to synchronize on the shared variable. Have main to wait on myVar notification before executing myMethod. Later, t1 can notify through variable myVar, and the waiting thread can continue and proceed with the method call.
The following snippet fully demonstrated the idea
public class MainPlay {
public static void main(String[] args) {
MainPlay mp = new MainPlay();
mp.execute();
}
public void execute() {
Thread main = new Thread(mainRunnable, "main");
Thread t1 = new Thread(t1Runnable, "t1");
main.start();
t1.start();
}
public Object myVar = new Object();
public void myMethod() {
System.out.println("MyMethodInfoked.");
}
public Runnable t1Runnable = new Runnable() {
public void run() {
synchronized(myVar) {
try {
System.out.println("[t1] sleep for 1 sec");
Thread.sleep(1000);
System.out.println("[t1] Notifying myVar so Main can invoke myMethod");
myVar.notify();
} catch (InterruptedException e) {
// interupted.
}
}
}
};
public Runnable mainRunnable = new Runnable() {
public void run() {
synchronized(myVar) {
try {
System.out.println("[main] Waiting for t1 to notify...");
myVar.wait();
} catch (InterruptedException e) {
// interrupted.
}
System.out.println("[main] executing main method");
myMethod();
}
}
};
}
And the output is
[main] Waiting for t1 to notify...
[t1] sleep for 1 sec
[t1] Notifying sharedObject so Main can invoke myMethod
[main] executing main method
MyMethodInfoked.
You could use wait/notify blocks to prevent the main thread from continuing until signalled to do so.
static Main main = // ...
static boolean signal = false;
// t1:
// Do work
signal = true;
synchronized (main) {
main.notify();
}
// main:
synchronized (main) {
while (!signal) {
main.wait();
}
}
myMethod();
In case the main thread has nothing else to do, the approach proposed by #searchengine27 results in unnecessary processor load generated by this thread.
So instead going with some AtomicXXX class it would be better to use some of the blocking queues which allow writing of data from one thread (with put()) and consumption of that data by the other. The main queue would block (by calling take() method) if such a queue is empty not using any CPU resources.
Hallo I've been debugging my code for a whole day already, but I just can't see where could be wrong.
I use SerialPortEventListener on a main thread, in a working thread I have a client socket communicating to a server.
Since after this working thread reach return, I still need some wrap up work done in the main thread, i want to create a "pseudothread" that wait in the main thread until the it is notified from the listener onEvent method.
but this pseudothread seems to be waiting forever.
I checked the locked thread pseudoThread, they should have the same object id in the Runnable and in Listener class.
"PseudoThread waiting" got displayed, but PseudoThread awake is never showed.
Console output shows:
PseudoThread waiting
..
..
false notified pseudothread.
PS if I create a lock in Main class with public final Object lock = new Object(); and replace all main.pseudoThread with main.lock, I get java.lang.IllegalMonitorStateException.
private class Pseudo implements Runnable{
Main main;
public Pseudo(Main main) {
this.main = main;
}
#Override
public void run() {
synchronized(main.pseudoThread){
try {
System.out.println("PseudoThread waiting");
main.pseudoThread.wait();
System.out.println("PseudoThread awake");
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
}
}
}
in main method:
public static void main(String[] args) {
Main main = new Main();
main.initArduino();
//more code. including starting the working thread
main.pseudoThread = new Thread(main.new Pseudo(main));
main.pseudoThread.start();
try {
main.pseudoThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void initArduino() {
arduino = new Arduino(this);
if(!arduino.initialize())
System.exit(1);
}
and in the listener class (which also runs in main thread)
//class constructor;
public Arduino(Main Main){
this.main = Main;
}
//listening method
public void serialEvent(SerialPortEvent oEvent){
//some code to interract with working thread.
record();
}
private void record(){
synchronized(main.pseudoThread){
main.pseudoThread.notify();
System.out.println("notified pseudothread.");
}
}
Without looking too deeply into what might actually be happening, I can see that your use of wait()/notify() is all wrong. Probably you are experiencing a "lost notification." The notify() function does nothing if there is no thread waiting for it at the moment when it is called. If your serialEvent() function calls notify() before the other thread calls wait(), then the notification will be lost.
Consider this example:
class WaitNotify() {
private final Object lock = new Object();
private long head = 0;
private long tail = 0;
public void consumer() {
synchronized (lock) {
while(head == tail) {
lock.wait();
}
doSomething();
count head += 1;
}
}
public void producer() {
synchronized (lock) {
tail += 1;
lock.notify();
}
}
}
The essential points are:
(1) The consumer() function waits for some relationship between data to become true: Here, it waits for head != tail.
(2) The consumer() function waits in a loop. There's two reasons for that: (a) Many programs have more than one consumer thread. If consumer A wakes up from the wait(), there's no guarantee that consumer B hasn't already claimed whatever it was that they both were waiting for. And (b) The Java language spec allows foo.wait() to sometimes return even when foo.notify() has not been called. That's known as a "spurious wakeup." Allowing spurious wakeups (so long as they don't happen too often) makes it easier to implement a JVM.
(3) The lock object is the same lock that is used by the program to protect the variables upon which the condition depends. If this example was part of a larger program, you would see synchronized(lock) surrounding every use of head and tail regardless of whether the synchronized code is wait()ing or notify()ing.
If your own code obeys all three of the above rules when calling wait() and notify(), then your program will be far more likely to behave the way you expect it to behave.
As suggested by james it could be lost notification case or it could be that.. Two Threads 1- Your Main Thread and 2- Pseudo thread Are waiting on the same Thread Instance Lock (main.pseudoThread)( Main thread waits on the same lock by calling join method).
Now you are using notify which wakes the Main thread from join method and not the one
waiting in your Pseudo. To check for the second case try calling notifyall in record this will either
confirm the second case or will rule this possibility.
Anyways please refactor your code not to use synch on Thread instance its bad practice. Go for ReentrantLock or CoundDownLatch something.
Usage of notify and wait seem to be incorrect. Method name notify can be a bit misleading because it is not for general purpose "notifying". These methods are used to control the execution of synchronization blocks. Wait will allow some other thread to synchronize with same object while current threads pauses. Basically this is used when some resource is not available and execution can not continue. On the other hand notify will wake one waiting thread wake from wait after notifying thread has completed its synchronized-block. Only one thread can be in synchronized block of the same object at the same time.
If the idea is just keep the main program running until notified then semaphore would be much more appropriate. Something like this.
public void run() {
System.out.println("PseudoThread waiting");
main.semaphore.acquireUninterruptibly();
System.out.println("PseudoThread awake");
}
//...
private void record(){
main.semaphore.release();
}
//...
public static void main(String[] args) {
main.semaphore = new Semaphore(0);
//...
}
Trying to wrap my head around this code. When I run this - the output will be Roger. Isn't msg a static variable and at a class level thus should print Moore?
EDIT : I've allowed a sleep too allow the child thread to run its course. It also prints printing... Still No Change
public class Test2 {
private static String msg = "Roger";
static {
new Thread(new Runnable() {
public void run() {
System.out.println("printing..");
msg += "Moore";
}
}).start();
}
static {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
public static void main(String argv[]) {
System.out.println(msg);
}
}
Trying to wrap my head around this code. When I run this - the output will be Roger. Isn't msg a static variable and at a class level thus should print Moore?
As others have pointed out, this is a race condition but it's more complicated then this simple answer.
EDIT : I've allowed a sleep too allow the child thread to run its course. It also prints printing... Still No Change
When a class is initialized, the static code is executed in the thread that accesses the class first – in this case the main thread. All other threads have to wait for this initialization to complete before they can access the class. This means that the background thread actually stops and waits for the class initialization to complete before it can execute msg += "Moore";. Then it is a race to see whether the msg is assigned to "Roger" and the background thread can append to it before main prints it. Even with the msg field being volatile, the race still exists. You can get a glimpse into the complexities of the process from the JLS section 12.4.2 on Detailed Initialization Procedure.
So what is happening is approximately:
The main thread initializes the Test2 class.
The msg is initialized first because it comes before the static blocks.
First static block is executed which forks the background thread.
Second static block is executed which does the sleep() blocking the initializing thread.
Background thread starts to run (could be before the previous step). It goes to update msg but the class is locked since the main thread is sleeping and hasn't completed with the class initialization. The background thread has to wait.
The main thread wakes up and finishes the initialization.
This releases the block on the class which allows the background thread to continue.
At the same time as the previous step, main is called and it is a race condition to see if the msg can be updated before it is printed out.
In general, forking background threads in static methods like this is extremely frowned upon. Putting a sleep in a static block is obviously not recommended as well.
The main method will not be called till all the static initializers in your class are done. So it will always wait till the static inits are done. Even if there is a sleep in it.
Additionaly static initialization is thread safe, so your forked thread cannot access the variable, till the static init blocks are done.
It's a race condition. There's no guarantee when the Runnable will have executed.
EDIT: This answers responds to the original posted question, in which no delay was present in the static initializer. This was leading to a simple race condition between the main thread reading the static member and the spawned thread updating it.
Rather than wait a little bit, and hope the other thread runs, you can guarentee it with some synchronization:
public class Test {
private static String msg = "Roger";
private static volatile boolean done = false;
private static final Object lock = new Object();
static {
new Thread(new Runnable() {
public void run() {
synchronized(lock)
{
lock.notify();
System.out.println("printing..");
msg += "Moore";
done=true;
}
}
}).start();
}
public static void main(String argv[]) {
synchronized(lock)
{
while(!done)
{
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println(msg);
}
}
If the main thread aquires the lock first, then it will msg.wait. It will not continue until notify is called(actually, it continues when the synchronized block containing notify finishes). If the new thread aquires the lock first, then the main thread will have to wait at the start of it's synchronization block. Once it gets in, done will be true. It will not wait, and go straight through.
I have the following codes. I expected one thread to execute its synchronized method completely and then allow another one to access the same method. However, this is not the case.
public class Threads {
/**
* #param args
*/
public static void main(String[] args) {
//Thread Th = new Threads();
Thread th = new Thread (new thread1 ());
th.start();
Thread th1 = new Thread (new thread1 ());
th1.start();
}
}
class thread1 implements Runnable{
String name = "vimal";
public void run() {
System.out.println("Runnable "+this.name);
setNAme("Manish");
}
public synchronized void setNAme(String name){
try {
System.out.println("Thread "+Thread.currentThread().getName());
wait(1000);
this.name = name;
System.out.println("Name "+this.name);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I have one output as
Runnable vimal
Thread Thread-0
Runnable vimal
Thread Thread-1
Name Manish
Name Manish
What is the use of synchronized here and how do I make my method to run completely before another accesses it?
synchronized has no effect here because you are not synchronizing on the same object in both cases. When applied to an instance method, the synchronized keyword causes the method to be synchronized on this. So in each case you are synchronizing on the instance of thread1, and there are two of those.
The more interesting test would be when you run the same instance of thread1 in two threads simultaneously. In that case, calling wait(1000) is a very bad thing to do because (as documented) it releases the lock on this. You want to use Thread.sleep(1000) instead in your code.
If you need to have two instances of thread1, you need to synchronize on some shared object, possibly like this:
private static final Object lockObject = new Object();
public void setName(String newName) {
synchronized(lockObject) {
doSetName(newName);
}
}
You will have to remove the call to wait(1000). It looks like what you actually want is a call to Thread.sleep(1000), if you simply want to pause the current thread, this does not release ownership of any monitors.
From the javadoc for Object.wait().
This method causes the current thread (call it T) to place itself in
the wait set for this object and then to relinquish any and all
synchronization claims on this object. Thread T becomes disabled for
thread scheduling purposes and lies dormant until one of four things
happens:
Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be
awakened.
Some other thread invokes the notifyAll method for this object.
Some other thread interrupts thread T.
The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time is not taken into
consideration and the thread simply waits until notified.
The thread T is then removed from the wait set for this object and
re-enabled for thread scheduling. It then competes in the usual manner
with other threads for the right to synchronize on the object; once it
has gained control of the object, all its synchronization claims on
the object are restored to the status quo ante - that is, to the
situation as of the time that the wait method was invoked. Thread T
then returns from the invocation of the wait method. Thus, on return
from the wait method, the synchronization state of the object and of
thread T is exactly as it was when the wait method was invoked.
UPDATE: As has been mentioned in other answers, you are not synchronizing on the same object. Once you do, you will still suffer the same output, due to the issue I have mentioned. You will need to fix both for your desired results.
The output is correct, you are creating to independent threads that do not share any data. Thus both threads start with first string, and after some time, the string is changed and printed.
You're creating 2 thread1 objects. They each have their own setNAme method. Synchronized methods only synchronize on the object, not the class. Unless the method is static.
You have two Threads here with independent name variables and independent monitors, so each Thread is only accessing its own members. If you want to have the threads interact with each other you'll have to implement such an interaction.
you are creating two separate thread1 objects and running them. Each thread has it's own copy of the name variable as well as the setName function. Make them both static and you will see the effects of synchronization.
You are locking on two different instance of the objects where you dont need any synchronization at all. You need to synchronize only if you are working on a shared data. I think you meant to write a test like the below.
If you test this, you will realize that the second thread will wait until the first thread is completed with the synchronized method. Then take out the synchronized word and you will see both threads are executing at the same time.
public class SynchronizeTest {
public static void main(String[] args) {
Data data = new Data();
Thread task1 = new Thread(new UpdateTask(data));
task1.start();
Thread task2 = new Thread(new UpdateTask(data));
task2.start();
}
}
class UpdateTask implements Runnable {
private Data data;
public UpdateTask(Data data) {
this.data = data;
}
public void run() {
try {
data.updateData();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Data {
public synchronized void updateData() throws InterruptedException {
for (int i = 0; i < 5; i++) {
Thread.sleep(5000);
System.out.println(i);
}
}
}