I've written a simple application, which has main thread(producer) and multiple consumer threads. I want to broadcast a message from main thread, so all the consumer threads will receive it. However, I have troubles. I'm trying to understand how Thread.sleep may be related to Happens-Before. Here's my piece of code:
import java.util.*;
public class PubSub {
public static void main(String[] args) {
List<Consumer> consumers = new ArrayList<>();
for (int i = 0; i < 3; i++ ) {
Consumer consumer = new Consumer(
"Consumer" + i
);
consumer.start();
consumers.add(consumer);
}
Scanner scanner = new Scanner(System.in);
while(true) {
String message = scanner.nextLine();
for (Consumer consumer: consumers) {
consumer.notify(message);
}
}
}
static class Consumer extends Thread {
private Queue<String> queue;
public Consumer(String name) {
super(name);
this.queue = new LinkedList<>();
}
@Override
public void run() {
while(true) {
if (!queue.isEmpty()) {
String message = queue.poll();
System.out.println(
getName() + ": Consuming message: " + message
);
}
}
}
public void notify(String message) {
queue.add(message);
}
}
}
If I add sleep, the consumer will start receiving messages:
@Override
public void run() {
while(true) {
try {
Thread.sleep(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (!queue.isEmpty()) {
String message = queue.poll();
System.out.println(
getName() + ": Consuming message: " + message
);
}
}
}
Since Thread.sleep is a native method, I want to understand how it resolves happens-before.
I must note, that the true way of fixing happens-before is to make volatile keyword:
private volatile Queue<String> queue;
If you add synchronization onto the queue, it will also fix the issue:
@Override
public void run() {
synchronized (queue) {
while (true) {
if (!queue.isEmpty()) {
String message = queue.poll();
System.out.println(
getName() + ": Consuming message: " + message
);
}
}
}
}
thread.sleep()
says nothing about "happens before" or "synchronization." I would therefore assume that there are no guarantees, and if I needed some form of synchronization, I would turn to some other mechanism to ensure it.