Which thread runs first? - java

In the following code,
public class Callme {
public Callme() {
// TODO Auto-generated constructor stub
}
void callA(String msg) throws InterruptedException
{
synchronized (this) {
System.out.print("["+msg);
Thread.sleep(1000);
}
System.out.println("]");
}
void callB(String msg) throws InterruptedException
{
synchronized (this) {
System.out.print("{"+msg);
Thread.sleep(1000);
}
System.out.println("}");
}
void callC(String msg) throws InterruptedException
{
synchronized (this) {
System.out.print("("+msg);
Thread.sleep(1000);
}
System.out.println(")");
}
}
Somewhere else:
public class Caller implements Runnable {
public char msg;
public Callme target;
public Thread t;
public Caller(char msg, Callme target) {
this.msg = msg;
this.target = target;
t= new Thread(this);
}
#Override
public void run() {
try {
switch (msg) {
case '[':
target.callA("Hello");
break;
case '{':
target.callB("Hello");
break;
case '(':
target.callC("Hello");
break;
default:
break;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Somewhere else:
Callme target = new Callme();
Caller ob1 = new Caller('[', target);
Caller ob2 = new Caller('{', target);
Caller ob3 = new Caller('(', target);
ob1.t.start();
ob2.t.start();
ob3.t.start();
Assuming callA runs first, after its synchronizedstatement is executed, in my trials, always ob1 next step is executed.
I thought sometimes ob2 synchronized step should be executed before that(at least sometimes).
Actual Output:
[Hello]
{Hello}
(Hello)
Expected Output:
[Hello(Hello]
)
{Hello}
Of course the order of {,[ and ( can vary and is not predictable.

Any job is restricted to adquire
synchronized (this) {
<<job>>
}
<<after>>
and any job must run <<job>> before <<after>>.
To be multiple <<after>> interleaved (<<job>> is impossible), one <<after>> must be blocked at least, until other later <<job>> and <<after>> will be executed. Using your code is very unlikely (<<after>> take the time to print one character but <<job>> take one second).
No matter how, how many and when the methods are called.
To produce the desired behavior, you must to add the blocking after the synchronized code and before the <<after>> code.
class Call {
public Call() {}
private static void delay(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
// keep out!
}
}
private void call(char a, String msg, char b) {
synchronized (this) {
System.out.print(a);
System.out.print(msg);
delay(100);
}
delay(ThreadLocalRandom.current().nextInt(10) * 10); // probability
System.out.println(b);
}
void callA(String msg) { call('[', msg, ']'); }
void callB(String msg) { call('{', msg, '}'); }
void callC(String msg) { call('(', msg, ')'); }
}
public class Callme {
static Call call = new Call();
static List<Consumer<String>> calls = asList(call::callA, call::callB, call::callC);
static void randomCall() {
calls.get(ThreadLocalRandom.current().nextInt(calls.size())).accept("Hello!");
}
public static void main(String... args) {
IntStream.range(0, 50).forEach(ignore -> new Thread(Callme::randomCall).start());
}
}
With outout:
(Hello!)
(Hello!)
)
{Hello!{Hello!}
{Hello!}
}
[Hello!(Hello!]
)
(Hello![Hello!)
{Hello!]
(Hello!}
[Hello!)
[Hello!]
]
(Hello![Hello!)
(Hello!]
[Hello!)
...

I would say the expected output is
[Hello]
{Hello}
(Hello)
Complete messages are expected because when leaving a synchronized block the code proceeds and immediately prints the closing character. Other threads do not continue that fast, first of all they have to get scheduled and then acquire the lock for the synchronized block, these steps take time
Thread.start() starts an OS-level thread (https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/java/lang/Thread.java#L673, https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/java/lang/Thread.java#L705, https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/native/java/lang/Thread.c#L44, https://github.com/openjdk-mirror/jdk7u-hotspot/blob/master/src/share/vm/prims/jvm.cpp#L2634, https://github.com/openjdk-mirror/jdk7u-hotspot/blob/master/src/share/vm/runtime/thread.cpp#L420, the chain ending with a system-dependent os::start_thread(thread); line), so ultimately it is up to the operating system how fast and in what order the threads will run, but typically they start running soon and in the order they have been requested to start
synchronized uses object monitors, and they build a list of the threads which are waiting for them (https://github.com/openjdk-mirror/jdk7u-hotspot/blob/master/src/share/vm/runtime/objectMonitor.cpp#L186 is the file, and the code is a bit out of this world, but the list itself is a linked list - well, a circular, doubly-linked one -, _waitSet, managed via the add/dequeue methods starting from https://github.com/openjdk-mirror/jdk7u-hotspot/blob/master/src/share/vm/runtime/objectMonitor.cpp#L2251). So notify() and notifyAll() walk through that list and wake up other threads in a deterministic order.

Related

Wait for another thread to do something

I have two threads, A and B. I want the following:
I want to let A wait until B starts executing f(). Once B starts executing f(), A as well can continue its work.
If B is already executing f() when A informs B for its state, A can continue its work as well.
If however B finished executing f(), A has to wait until B starts executing f() again in the future.
In functions:
// executed by A only
public void waitForB() throws InterruptedException {
// keep waiting until B starts f()
}
// executed within aroundF() only
public void f() {
}
// executed by B only
public void aroundF() {
// 1. mark that we are executing f() and inform A
f()
// 2. unmark
}
I have been trying with Semaphore, Phaser and CyclicBarrier, but I have troubles to understand which to use here.
I managed to implement this with locking manually (see below), but I would like to understand which of the java.util.concurrent classes to use here.
private final Object lock = new Object();
private boolean executing = false;
public void waitForB() throws InterruptedException {
synchronized(lock) {
while(!executing) {
lock.wait();
}
}
}
public void f() {
}
public void aroundF() {
try {
synchronized(lock) {
executing = true;
lock.notify();
}
f();
} finally {
executing = false;
}
}
You can achieve the same semantics (and more) using java.util.concurrent.locks.Lock and an associated java.util.concurrent.locks.Condition, for instance:
public class MyClass {
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
private boolean executing = false;
public void waitForB() throws InterruptedException {
lock.lock();
try {
while (!executing) {
condition.await();
}
} finally {
lock.unlock();
}
}
public void f() {
}
public void aroundF() {
try {
lock.lock();
try {
executing = true;
condition.signal();
} finally {
lock.unlock();
}
f();
} finally {
executing = false;
}
}
}

Is it possible to write a guaranteed classic deadlock with synchronized methods?

I was asked at an interview to write java code which is guaranteed deadlock. I wrote a standard code which presents at every Java book, like create 2 threads and call synchronized methods at different order, sleep a little before call the 2nd.
Of course this stuff didn't satisfy the interviewers, so now I'm proceeding to figure the solution out.
I discovered a piece of code:
public class Lock implements Runnable {
static {
System.out.println("Getting ready to greet the world");
try {
Thread t = new Thread(new Lock());
t.start();
t.join();
} catch (InterruptedException ex) {
System.out.println("won't see me");
}
}
public static void main(String[] args) {
System.out.println("Hello World!");
}
public void run() {
try {
Thread t = new Thread(new Lock());
t.start();
t.join();
} catch (InterruptedException ex) {
System.out.println("won't see me");
}
}
}
But I'm not sure if this code satisfied them? Sure. The code never ends execution, but is it a true deadlock? Aren't deadlocks about synchronization? And, for example, I can also write an endless cycle, put a Thread.sleep inside and name it a "deadlock".
So the question is: is it possible to write a classic deadlock using synchronized methods but 100% guaranteed? (Please don't tell me about very, very, very likely deadlock cases. I know it.)
Thanks.
Create two resources, and have each thread try to get one before releasing the other, but in different orders. For instance:
CountDownLatch a = new CountDownLatch (1);
CountDownLatch b = new CountDownLatch (1);
void one() throws InterruptedException {
a.await();
b.countDown();
}
void two() throws InterruptedException {
b.await();
a.countDown();
}
The thread that runs one can't release b, because it's waiting for a. It'll wait forever, because the thread that runs two can't release a because it's waiting for b.
One or the classic deadlock scenarios is when you acquire locks in reverse order.
class Resource1 {
synchronized static void method1() {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
Resource2.method1();
}
}
class Resource2 {
synchronized static void method1() {
Resource1.method1();
}
}
public class MultiThreadApp {
public static void main(String[] args) {
new Thread(new Runnable() {
public void run() {
Resource2.method1();
}
}).start();
Resource1.method1();
}
}
public class Deadlock {
public static void main(String[] args) {
String res1 = "a";
String res2 = "s";
new Thread(
() -> {
synchronized (res1) {
try {
Thread.sleep(2);
} catch (InterruptedException e) {
}
synchronized (res2) {
}
}
}
).start();
new Thread(
() -> {
synchronized (res2) {
try {
Thread.sleep(2);
} catch (InterruptedException e) {
}
synchronized (res1) {
}
}
}
).start();
}
}

Is this interrupt() necessary?

Here's the snippet:
public class LogService {
public void stop() {
synchronized (this) { isShutdown = true; }
loggerThread.interrupt(); /* Is it necesarry? */
}
public void log(String msg) throws InterruptedException {
synchronized (this) {
if (isShutdown)
throw new IllegalStateException(...);
++reservations;
}
queue.put(msg);
}
private class LoggerThread extends Thread {
public void run() {
try {
while (true) {
try {
synchronized (LogService.this) {
if (isShutdown && reservations == 0)
break;
}
String msg = queue.take();
synchronized (LogService.this) {
--reservations;
}
writer.println(msg);
} catch (InterruptedException e) { } /* Do nothing */
}
} finally {
writer.close();
}
}
}
}
As the code above, Even if we put LoggerThread.interrupt() in stop() method, the interruption just be caught by thread and do nothing.
So is LoggerThread.interrupt() necessary?
Yes it it necessary. If the queue is empty, this statement String msg = queue.take(); will block until an element is put in the queue or it is is interrupted.
If you want to guarantee that the thread does not hang you need to interrupt it.
However there seems to be a glitch: if reservations is not 0 when you call the close method AND the queue is empty, it seems that your loop will keep going and hang on queue.take() at the while loop iteration following the interruption.

Do I correctly shutdown these simultaneous threads

As in the subject do I correctly shutdown these simultaneous threads?
I assigned a volatile field and check it repeatedly in while loop.
Is there alternative way to do it(like using synchronize or wait() method), please show me.
EDIT I edited code. Is there any way of checking if Thread is alive by different method thatn isAlive();?
Perhaps:
boolean isAlive(){
return running;
}
import javax.swing.JOptionPane;
public class Wat extends Thread {
private char c;
private int interv;
private volatile boolean running = true;
Object synchObj;
public Wat(char c, int interv) {
this.c = c;
this.interv = interv;
synchObj = new Object();
}
public void run() {
while (running) {
synchronized (synchObj) {
try {
showChar(c);
synchObj.wait(interv * 100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public synchronized static void showChar(char c) {
System.out.println(c);
}
public void shutdown() {
running = false;
synchronized (synchObj) {
synchObj.notify();
}
}
public static void main(String[] args) throws InterruptedException {
Wat w1 = new Wat('A', 3);
Wat w2 = new Wat('B', 4);
Wat w3 = new Wat('C', 5);
w1.start();
w2.start();
w3.start();
Object[] options = { "Shutdown A", "Shutdown B", "Shutdown C" };
int option;
while (w1.isAlive() || w2.isAlive() || w3.isAlive()) {
option = JOptionPane.showOptionDialog(null,
"Which one would you like to shut?", "Threads",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options, options[2]);
switch (option) {
case JOptionPane.YES_OPTION:
w1.shutdown();
break;
case JOptionPane.NO_OPTION:
w2.shutdown();
break;
case JOptionPane.CANCEL_OPTION:
w3.shutdown();
break;
}
Thread.sleep(1);
}
}
}
Your code will probably work fine, but the Thread.sleep is not very elegant. I would do something along these lines, calling the shutdown() method to quit the thread
Object synchObj = new Object();
public void run() {
while (running) {
synchronized (synchObj) {
try {
System.out.println(new Date());
synchObj.wait(5000);
} catch (InterruptedException e) {
// error handling
}
}
}
}
public void shutdown() {
running = false;
synchronized (synchObj) {
synchObj.notify();
}
}
public static void main(String[] args) throws InterruptedException,
IOException {
ThreadTest test = new ThreadTest();
test.start();
BufferedReader tReader = new BufferedReader(new InputStreamReader(
System.in));
tReader.readLine();
test.shutdown();
}
EDIT added test code
Yes, you are closing the threads correctly. The only comment is that you are breaking the encupsulation here because the flag running is accessed directly. I'd recommend you to add method shutdown() that changes this flag to false.
EDIT.
I have just noticed that you are calling sleep() inside the loop. This is indeed bad practice in most cases. You should probably call wait(timeout). In this case your shutdown() method will change the flag to false and then call notify() on same monitor. This will cause your thread to exit immediately.
It seems the program is perfect, uses volatile boolean variable and makes it false.
synchronized need only multi thread access. instead of sleep you can use wait, it has a object access rather than static sleep, also any time you can interrupt the waiting.

How to solve this thread blocking issue

I'm testing a Java multi-threading sample code but the thread started in the for loop of qB.start() is blocked because it's waiting for entry of qB monitor. What is the cause of this blockage?
Thank you.
import java.util.*;
class QA {
public synchronized void open() throws Exception {
Thread o = new Thread() {
public void run() {
QB qB = new QB();
qB.start();
}
};
o.start();
}
public static void main(String args[]) throws Exception {
new QA().open();
}
public class QB {
private boolean shutdown;
private Vector<Thread> tList;
private final Object waitingLock = new Object();
public QB() {
tList = new Vector<Thread>();
}
public synchronized void start() {
for(int i = 0; i < 1; i++) {
final int id = i;
Thread t = new Thread("Thread " + id) {
public void run() {
load(id);
}
};
tList.add(i, t);
t.start();
}
tMonitor();
waitUntilFinished();
}
private void tMonitor() {
Thread cmt = new Thread("T Monitor Thread") {
public void run() {
synchronized(waitingLock) {
while(tList.size() > 0) {
try {
sleep(10000);
} catch(Exception e) {
e.printStackTrace();
}
}
waitingLock.notifyAll();
}
}
};
cmt.start();
}
private void waitUntilFinished() {
synchronized(waitingLock) {
while(!isShutDown()) {
try {
waitingLock.wait();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
private synchronized void load(int id) {
try {
System.out.println("blocked here");
// some work done here
removeFromTList(id);
} catch(Exception e) {
e.printStackTrace();
}
}
public synchronized boolean isShutDown() {
return shutdown;
}
}
}
The first problem I see is that QB#start() is synchronized on the instance of QB.
Inside the thread t that you are trying to spawn, load(id) is also synchronized on the same instance of QB. So when you call t.start() the t thread blocks until QB#start() finishes.
Presumably, at the end of the QB#start() method, QB#waitUntilFinished() is supposed to wait for all the t threads to finish, but they can't even enter the QB#load method because they're still waiting for the QB#start() method to release the lock on the QB instance.
So, circular deadlock.
Edit:
Ok, now that we see how the threads are removed from tList the bug is fully revealed.
If the index 0 thread finishes first then it will remove itself from the list. That means when the index 1 thread finishes, it will remove the 1th position from the Vector but that does not point to itself anymore. It is removing the #2 thread. Sooner or later you are going to get an exception when the remove happens because it is going to be removing an invalid index.
You need to remove items from the Vector by address and not by position:
tList.remove(this);
That will remove the current thread from the list. You should also just do an add(t) instead of an add(i t) in the start loop:
tList.add(t);
You now don't need the id position passed into your thread at all.
I don't see where you are removing the finished threads from your tList. I see a definition (not that you edited your OP) of a removeFromTList() method but I don't see it used anywhere. In tMonitor you are in a while loop here:
while(tList.size() > 0) {
try {
sleep(10000);
} catch(Exception e) {
e.printStackTrace();
}
}
// you never get to this line
        waitingLock.notifyAll();
But I don't see anything that removes the thread from the list. Maybe when the threads each finish they are supposed to remove themselves?
If tMonitor thread never gets out of that loop then it never calls:
waitingLock.notifyAll();
So the main thread will hang forever in waitUntilFinished();.
synchronized(waitingLock) {
while(!isShutDown()) {
try {
waitingLock.wait();
} catch(Exception e) {
e.printStackTrace();
}
}
Also, you don't want to do a sleep in tMonitor() because you are in a synchronized block. You should be doing a:
waitingLock.wait(10000);
Nothing will ever notify it but it's bad form to hold the lock like that in a sleep.

Categories