Thread got suspended after the put operation in SynchronousQueue - java

This is my code
import java.util.concurrent.SynchronousQueue;
public class Mywork {
public static void main(String args[])
{
SynchronousQueue<String> s=new SynchronousQueue<>();
Producer1 p1 =new Producer1(s);
Producer2 p2=new Producer2(s);
new Thread(p1).start();
new Thread(p2).start();
}
}
class Producer1 implements Runnable
{
SynchronousQueue<String> s=null;
Producer1(SynchronousQueue<String> q)
{
this.s=q;
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
s.put("Suman");
System.out.println(s);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//
class Producer2 implements Runnable
{
SynchronousQueue<String> s=null;
Producer2(SynchronousQueue<String> q)
{
this.s=q;
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
s.put("Ghosh");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
whenever the put is performed after that I am not ale to debug it , the control vanishes from the eclipse
any idea why it is happening ?

From the doc:
The put method will block until another thread retrieved data from SynchronousQueue.

put(E o)
Adds the specified element to this queue, waiting if necessary for
another thread to receive it.
That said, SynchronousQueue will not return until there is a corresponding take() call. And, you are adding element in both thread and caused wait.
So, changing
s.put("Ghosh");
to
String str = s.take();
will continue execution.

Related

Use of Notify Method in Multithreading

I am learning multithreading.
I tried to implement producer consumer problem in Java.Its working fine.
But if i remove notify call the program goes into a deadlock state.Why?
Its going on deadlock when size of queue becomes 0.Ideally when size becomes 0,wait should be called inside consumer and producer should started working.
import java.io.*;
import java.util.*;
class Consumer implements Runnable{
Queue<Integer> q;
int n;
public void run() {
while(true){
synchronized (q) {
while(q.size()==0){
try {
System.out.println("q.size="+q.size());
q.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("item consumed="+q.poll());
q.notify();
try {
Thread.sleep((int)(Math.random() * 100));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Consumer(Queue<Integer> queue,int n){
q=queue;
this.n=n;
}
}
class Producer implements Runnable{
Queue<Integer> q;
int n;
public void run() {
int x=1;
while(true){
synchronized (q) {
while(q.size()==n){
try {
q.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("item produced="+x+" q.size="+q.size());
q.add(x++);
q.notify();
try {
Thread.sleep((int)(Math.random() * 100));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Producer(Queue<Integer> queue,int n){
q=queue;
this.n=n;
}
}
public class App
{
public static void main( String[] args ) throws InterruptedException
{
int n=100;
Queue<Integer> q=new LinkedList<Integer>();
Thread t1=new Thread(new Producer(q, n));
Thread t2=new Thread(new Consumer(q, n));
t1.start();
t2.start();
t1.join();
t2.join();
}
}
you required notify because when one thread is on wait state because queue is empty or full come to running state if some other thread notify after putting if queue is empty and taking queue is full.
put q.wait(10); so your code will not go on deadlock because after time it will check while loop condition.
It is always best practice to use notify in above usecase

How to write guaranteed deadlock via wait/notify

I visited interview some recently. Interviewer asked me to write guaranteed deadlock.
I have wrote following:
public class DeadLockThreadSleep {
private static class MyThread implements Runnable {
private Object o1;
private Object o2;
#Override
public void run() {
try {
test(o1, o2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public MyThread(Object o1, Object o2) {
this.o1 = o1;
this.o2 = o2;
}
public void test(Object o1, Object o2) throws InterruptedException {
synchronized (o1) {
System.out.println("1.acquired: " + o1);
Thread.sleep(1000);
synchronized (o2) {
System.out.println("2.acquired: " + o2);
}
}
}
}
public static void main(String[] args) {
Object o1 = new Object();
Object o2 = new Object();
new Thread(new MyThread(o1, o2)).start();
new Thread(new MyThread(o2, o1)).start();
}
}
Then he asked if I sure that it is guaranted. I rememebered that Thread.sleep nothing guaranteed.
Then I wrote this code:
public static void main(String[] args) {
final Thread mainThread = Thread.currentThread();
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
mainThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this answer was accepted.
Also he asked to write analog via wait/notify. I thought a lot and I cannot imagine how to write this.
Is it possible?
This may be done by creating a cycle where one thread holds a resource and waits for another resource whereas the other thread does the same but in reverse order.
Thread tholds resourceOne and waits for resourceTwo , whereas t1holds resourceTwo and waits for resourceOne
Below is a sample code:
public class WaitNotifyLock {
boolean isONHold = false;
public synchronized void hold(){
while(isONHold){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
isONHold = true;
System.out.println(Thread.currentThread().getId() + " : Holded");
}
public synchronized void unHold(){
while(!isONHold){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getId() + " : Produced");
isONHold = false;
notify();
}
public static void main(String[] args) {
WaitNotifyLock resourceOne = new WaitNotifyLock();
WaitNotifyLock resourceTwo = new WaitNotifyLock();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
resourceOne.hold();
try {
Thread.sleep(2);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
resourceTwo.hold();
resourceOne.unHold();
resourceTwo.unHold();
}
});
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
resourceTwo.hold();
try {
Thread.sleep(2);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
resourceOne.hold();
resourceTwo.unHold();
resourceOne.unHold();
}
});
t.start();
t1.start();
}
}
A deadlock is a so-called liveness hazard (others are starvation, poor responsiveness, or livelocks), where two main types can be considered:
Lock-ordering deadlocks
Resource deadlocks
However, the Java documentation simplifies this as follows:
Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.
Hence, IMHO you could simply enforce a deadlock with this:
public class DeadlockDemo {
public static void main(String[] args) {
Object a = new Object();
Object b = new Object();
new Thread(() -> waitLeftNotifyRight(a, b)).start();
waitLeftNotifyRight(b, a);
}
public static void waitLeftNotifyRight(Object left, Object right) {
synchronized (left) {
try {
System.out.println("Wait");
left.wait();
} catch (InterruptedException e) { /* NOP */ }
}
synchronized (right) {
System.out.println("Notify");
right.notify();
}
}
}
This demo never terminates because the created thread waits on a's monitor, whereas the main thread waits on b's monitor. As a result, the corresponding notify() methods aren't invoked (which would terminate the program).

Daemon thread not working as expected

package main.components;
import java.io.Serializable;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class MainSnoozerx implements Runnable, Serializable {
private static final long serialVersionUID = 1L;
private static int min = 0;
static Thread mnz = new Thread(new MainSnoozerx());
private long convertedToMiliSec = 0l;
private Scanner scn = new Scanner(System.in);
#Override
public void run() {
// TODO Auto-generated method stub
try{
do{
System.out.println("Enter minutes to snooze..");
min = scn.nextInt();
}while(min<0);
convertedToMiliSec = TimeUnit.MINUTES.toMillis(min);
try {
Thread.sleep(convertedToMiliSec);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Alarm Now!!!");
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
mnz.setDaemon(true);
mnz.start();
}
}
Can anyone tell me what am I doing wrong/missing?
My program just terminates when I run it without printing the syso even once.
I expect the code to run endlessly being a daemon thread and the user just sets the mins once and the snooze goes on forever...
You've got it the wrong way around, the JVM will keep running while there is at least one non-daemon thread alive. The main thread is not a daemon thread and if no other non-daemon threads are created before the main thread exits the JVM will exit.
If you want the JVM to keep running, remove the setDaemon call
You fired the thread without ever tell Java that you want the work done back. You need to add a mnz.join() after your start ;)
With that fix, your thread run one time for sure. If you decide to put all your run() code inside of a while loop and change your loop, you got the behaviour that you want.
Like this
#Override
public void run() {
while (true) {
// TODO Auto-generated method stub
try {
while (min == 0) {
System.out.println("Enter minutes to snooze..");
min = scn.nextInt();
}
convertedToMiliSec = TimeUnit.MINUTES.toMillis(min);
try {
Thread.sleep(convertedToMiliSec);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Alarm Now!!!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
mnz.setDaemon(true);
mnz.start();
mnz.join();
}

Threads running at same time instance

I have a requirement threading where I need to initiate a thread which will run continuously doing some DB operations . A second thread will be present which needs to run for every 30 secs. The job of the second thread will be killing the first thread and start a new instance of the first thread.
I tried several ways to achieve this but I am not able to do the same.
public class ThreadMain {
public static void main(String[] args) throws InterruptedException, BrokenBarrierException{
final CyclicBarrier gate = new CyclicBarrier(3);
Thread t1 = new Thread(){
public void run(){
try {
gate.await();
while(true)
{
System.out.println("Thread1");
break;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
Thread t2 = new Thread(){
public void run(){
try {
gate.await();
while(true)
{
System.out.println("Continiously running thread:-Thread2");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
t1.start();
t2.start();
This seems to work nicely:
// Thread that runs forever.
volatile static Thread forEverThread = null;
static class ForEver implements Runnable {
#Override
public void run() {
try {
while (true) {
Thread.sleep(1000);
System.out.println("For Ever!");
}
} catch (InterruptedException ex) {
// Just quit if I was interrupted.
}
}
}
// Stop the thread if it is running.
private static void stopForeverThread() throws InterruptedException {
// Skip if non-existent.
if (forEverThread != null) {
// Make sure no-one else is already doing it.
synchronized (forEverThread) {
// Still not null?
if (forEverThread != null) {
// Interrupt it.
forEverThread.interrupt();
// Wait for it to finish.
forEverThread.join();
// Clear it.
forEverThread = null;
}
}
}
}
private static void restartForeverThread() throws InterruptedException {
System.out.println("Restarting...");
// Stop it if it is running.
stopForeverThread();
// Start it again.
forEverThread = new Thread(new ForEver());
forEverThread.start();
System.out.println("Restarted");
}
public static void start() throws InterruptedException {
// Start it all up.
restartForeverThread();
// Timed event to restart it.
Timer restartTimer = new Timer(true);
restartTimer.scheduleAtFixedRate(
new TimerTask() {
#Override
public void run() {
try {
// Restart every few seconds.
restartForeverThread();
} catch (InterruptedException ex) {
// We were interrupted during restart - Log it.
}
}
// Every few seconds.
}, 0, 10 * 1000);
}
public static void main(String args[]) {
try {
// Start it all up.
start();
// Hang around for a while - to see what happens.
Thread.sleep(60 * 1000);
} catch (Throwable t) {
t.printStackTrace(System.err);
}
}
If your database task is interruptible (i.e. it reacts on thread interruption and hence can be cancelled by that), the best strategy is to use an ScheduledExecutorService for both, the database task itself and the restart task that runs periodically.
Note that task and thread are two different things: While a task is a piece of work that should be run, threads are the mechanism to do this in parallel.
static class DatabaseTask implements Runnable {
public void run() {
...
}
}
static class RestartTask implements Runnable {
private final ExecutorService executor;
private volatile Future<Void> future;
public RestartTask(ExecutorService executor) {
this.executor = executor;
}
public void run() {
if (future != null) {
future.cancel(true);
}
future = executor.submit(new DatabaseTask());
}
}
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(new RestartTask(executor), 0, 30, TimeUnit.SECONDS);
Note that if your DatabaseTask is NOT sensitive to thread interruption and continues to perform database operations, the number of threads executing database tasks will grow continously - probably not what you want. So make sure, all blocking database operations are either interruptible, or terminate within a reasonable amount of time.

multithreading in Java with 2 threads spawned

I wrote a Multithreaded program in Java given below :-
public class Client {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Counter counter = new Counter();
int val = counter.getValue();
while(val < 5){
val = counter.getValue();
System.out.println("In main thread : "+val);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Counter implements Runnable {
private int countValue;
Counter(){
countValue = 0;
Thread thread = new Thread(this ,"Counter A");
Thread thread1 = new Thread(this ,"Counter B");
thread.start();
thread1.start();
}
int getValue(){
return countValue;
}
#Override
public void run() {
// TODO Auto-generated method stub
while( countValue < 5){
System.out.println("In child thread : "+ ++countValue );
try {
Thread.sleep(250);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
and output of program is
output :-
In main thread : 0
In child thread : 2
In child thread : 1
In child thread : 3
In child thread : 3
In child thread : 4
In child thread : 5
In main thread : 5
Can anybody explain me in detail how this output came.Thank you in advance
You have 3 threads (main and 2 child) that are all running in parallel (unless you have a single proc box) that are all reading and writing a resource countValue that isn't protected by any kind of synchronization.
When you do things like this, you'll get apparently random output.

Categories