Last active
February 5, 2019 15:49
-
-
Save tofti/7a3aba2ff09f2c2df94192e9a79e005e to your computer and use it in GitHub Desktop.
Creating deadlocks when using notify, rather than notifyAll.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tofti.java.popularquestions; | |
import java.util.LinkedList; | |
import java.util.Queue; | |
import java.util.concurrent.atomic.AtomicLong; | |
public class NotifyNotifyAll { | |
static class Buffer<T> { | |
static final int MAX_CAPACITY = 1; | |
Queue<T> buff = new LinkedList<>(); | |
AtomicLong puts = new AtomicLong(); | |
AtomicLong gets = new AtomicLong(); | |
public synchronized void put(T v) throws InterruptedException { | |
while(buff.size() == MAX_CAPACITY) { | |
wait(); | |
} | |
buff.add(v); | |
if(puts.incrementAndGet() % 1_000 == 0) { | |
System.err.println("puts=" + puts); | |
} | |
notify(); | |
//notifyAll(); | |
} | |
public synchronized T get() throws InterruptedException { | |
while(buff.isEmpty()) { | |
wait(); | |
} | |
T t = buff.poll(); | |
//notifyAll(); | |
notify(); | |
if(gets.incrementAndGet() % 1_000 == 0) { | |
System.err.println("gets=" + gets); | |
} | |
return t; | |
} | |
} | |
public static void main(String[] args) { | |
final Buffer<Long> buff = new Buffer<>(); | |
class Producer implements Runnable { | |
volatile boolean complete = false; | |
@Override | |
public void run() { | |
while(!complete) { | |
try { | |
buff.put(System.nanoTime()); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
void terminate() { | |
complete = true; | |
} | |
} | |
class Consumer implements Runnable { | |
volatile boolean complete = false; | |
@Override | |
public void run() { | |
while(!complete) { | |
try { | |
Long aLong = buff.get(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
void terminate() { | |
complete = true; | |
} | |
} | |
new Thread(new Producer(),"producer-1").start(); | |
new Thread(new Consumer(),"consumer-1").start(); | |
new Thread(new Producer(),"producer-2").start(); | |
new Thread(new Consumer(),"consumer-2").start(); | |
System.err.println(Thread.getAllStackTraces()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment