STIW3054-A172 / Main-Issues

1 stars 1 forks source link

Exercise_12 #13

Open zhamri opened 6 years ago

zhamri commented 6 years ago

Write a Java program using TWO (2) threads to simulate Livelock.

AsadRazali commented 6 years ago

public class Livelock {

    public static void main (String[] args) {
        final Worker worker1 = new Worker("Worker 1 ", true);
        final Worker worker2 = new Worker("Worker 2", true);

        final CommonResource s = new CommonResource(worker1);

        new Thread(() -> {
            worker1.work(s, worker2);
        }).start();

        new Thread(() -> {
            worker2.work(s, worker1);
        }).start();
    }
}
public class Worker {
    private String name;
    private boolean active;

    public Worker (String name, boolean active) {
        this.name = name;
        this.active = active;
    }

    public String getName () {
        return name;
    }

    public boolean isActive () {
        return active;
    }

    public synchronized void work (CommonResource commonResource, Worker otherWorker) {
        while (active) {
            // wait for the resource to become available.
            if (commonResource.getOwner() != this) {
                try {
                    wait(10);
                } catch (InterruptedException e) {
                   //ignore
                }
                continue;
            }

            // If other worker is also active let it do it's work first
            if (otherWorker.isActive()) {
                System.out.println(getName() +
                            " : handover the resource to the worker " +
                                                       otherWorker.getName());
                commonResource.setOwner(otherWorker);
                continue;
            }

            //now use the commonResource
            System.out.println(getName() + ": working on the common resource");
            active = false;
            commonResource.setOwner(otherWorker);
        }
    }
}
public class CommonResource {
    private Worker owner;

    public CommonResource (Worker d) {
        owner = d;
    }

    public Worker getOwner () {
        return owner;
    }

    public synchronized void setOwner (Worker d) {
        owner = d;
    }
}

capture

liiyanamegat commented 6 years ago

Source Code


package rt_issues;

public class RT_Issues13 {

    static class Spoon {
        private Diner owner;
        public Spoon(Diner d) { owner = d; }
        public Diner getOwner() { return owner; }
        public synchronized void setOwner(Diner d) { owner = d; }
        public synchronized void use() { 
            System.out.printf("%s has eaten!", owner.name); 
        }
    }

    static class Diner {
        private String name;
        private boolean isHungry;

        public Diner(String n) { name = n; isHungry = true; }       
        public String getName() { return name; }
        public boolean isHungry() { return isHungry; }

        public void eatWith(Spoon spoon, Diner spouse) {
            while (isHungry) {
                // Don't have the spoon, so wait patiently for spouse.
                if (spoon.owner != this) {
                    try { Thread.sleep(1); } 
                    catch(InterruptedException e) { continue; }
                    continue;
                }                       

                // If spouse is hungry, insist upon passing the spoon.
                if (spouse.isHungry()) {                    
                    System.out.printf(
                        "%s: You eat first my darling %s!%n", 
                        name, spouse.getName());
                    spoon.setOwner(spouse);
                    continue;
                }

                // Spouse wasn't hungry, so finally eat
                spoon.use();
                isHungry = false;               
                System.out.printf(
                    "%s: I am stuffed, my darling %s!%n", 
                    name, spouse.getName());                
                spoon.setOwner(spouse);
            }
        }
    }

    public static void main(String[] args) {
        final Diner husband = new Diner("Bob");
        final Diner wife = new Diner("Alice");

        final Spoon s = new Spoon(husband);

        new Thread(new Runnable() { 
            public void run() { husband.eatWith(s, wife); }   
        }).start();

        new Thread(new Runnable() { 
            public void run() { wife.eatWith(s, husband); } 
        }).start();
    }
}

Output image

kzkit commented 6 years ago

SourceCode

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package real_time;

/**
 *
 * @author master lab
 */
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TrafficSignal_Livelock {
    private String signal;
    private String roadName;
    private Lock lock = new ReentrantLock();
    private final static String GREEN = "Green";
    private final static String RED = "Red";

    public TrafficSignal_Livelock(String roadName, String signal) {
        this.roadName = roadName;
        this.signal = signal;
    }

    private boolean green(TrafficSignal_Livelock road) {
        if (this.lock.tryLock()) {
            System.out.println("Show Signal of " + road.roadName + " - "
                    + road.signal);
            try {
                Thread.sleep(10l);
            } catch (InterruptedException e) {
            }
            this.signal = GREEN;
            return true;
        }
        return false;
    }

    private boolean red(TrafficSignal_Livelock road) {
        if (this.lock.tryLock()) {
            System.out.println("Show Signal of " + road.roadName + " - "
                    + road.signal);
            try {
                Thread.sleep(10l);
            } catch (InterruptedException e) {
            }
            this.signal = RED;
            return true;
        }
        return false;
    }

    public static boolean changeSignal(TrafficSignal_Livelock road1,
            TrafficSignal_Livelock road2) {
        if (road1.red(road1)) {
            if (road2.green(road2)) {
                return true;
            } else {
                // can't make it green than go for red.
                road1.green(road1);
                return false;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        final TrafficSignal_Livelock xRoad = new TrafficSignal_Livelock(
                "X-Road", GREEN);
        final TrafficSignal_Livelock yRoad = new TrafficSignal_Livelock(
                "Y-Road", RED);

        Thread thread1 = new Thread("signal-1") {
            public void run() {
                int counter = 0;
                while ((!TrafficSignal_Livelock.changeSignal(xRoad, yRoad))) {
                    counter = counter + 1;
                    continue;
                }
                System.out.printf("%s completed ", Thread.currentThread()
                        .getName());
            }
        };
        Thread thread2 = new Thread("signal-2") {
            public void run() {
                int counter = 0;
                while ((!TrafficSignal_Livelock.changeSignal(yRoad, xRoad))) {
                    counter = counter + 1;
                    continue;
                }
                System.out.printf("%s completed ", Thread.currentThread()
                        .getName());
            }
        };
        thread1.start();
        thread2.start();
    }
}

Screenshot

abca

References https://www.vikastechblog.com/java/multithreading/deadlock-livelock-starvation.html

Shanthini21 commented 6 years ago

Criminal class

package stiw3054_12;

/*

Police class

public class Police { private boolean moneySent = false;

public void giveRansom(Criminal criminal) {

    while (!criminal.isHostageReleased()) {

        System.out.println("Police: waiting criminal to release hostage");

        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    System.out.println("Police: sent money");

    this.moneySent = true;
}

public boolean isMoneySent() {
    return this.moneySent;
}

}

Test Class

public class HostageRescueLivelock { static final Police police = new Police();

static final Criminal criminal = new Criminal();

public static void main(String[] args) {

    Thread t1 = new Thread(new Runnable() {
        public void run() {
            police.giveRansom(criminal);
        }
    });
    t1.start();

    Thread t2;
    t2 = new Thread(new Runnable() {
        public void run() {
            criminal.releaseHostage(police);
        }
    });
    t2.start();
}

} i12

nurulbasitah commented 6 years ago
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author hp
 */
public class Criminal {
  private boolean hostageReleased = false;

    public void releaseHostage(Police police) {
        while (!police.isMoneySent()) {

            System.out.println("Criminal: waiting police to give ransom");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }

        System.out.println("Criminal: released hostage");

        this.hostageReleased = true;
    }

    public boolean isHostageReleased() {
        return this.hostageReleased;
    }   

}
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author hp
 */
class Police {
     private boolean moneySent = false;

    public void giveRansom(Criminal criminal) {

        while (!criminal.isHostageReleased()) {

            System.out.println("Police: waiting criminal to release hostage");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }

        System.out.println("Police: sent money");

        this.moneySent = true;
    }

    public boolean isMoneySent() {
        return this.moneySent;
    }

}

public class HostageRescueLivelock {
    static final Police police = new Police();

    static final Criminal criminal = new Criminal();

    public static void main(String[] args) {

        Thread t1 = new Thread(new Runnable() {
            public void run() {
                police.giveRansom(criminal);
            }
        });
        t1.start();

        Thread t2 = new Thread(new Runnable() {
            public void run() {
                criminal.releaseHostage(police);
            }
        });
        t2.start();
    }

}

livelock

References:

  1. http://www.codejava.net/java-core/concurrency/understanding-deadlock-livelock-and-starvation-with-code-examples-in-java
naimsaleh commented 6 years ago

import java.util.concurrent.locks.ReentrantLock;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author master lab
 */
public class LiveLock {

    public static void main(String[] args) {
        Account acct1 = new Account(101, 5000);
        Account acct2 = new Account(102, 7000);
        // Creating two threads
        Thread thread1 = new Thread(new Operation(acct1, acct2, 100));
        Thread thread2 = new Thread(new Operation(acct2, acct1, 100));

        thread1.start();
        thread2.start();
    }

}

class Account{
    int acctNum;
    int balance;
    ReentrantLock lock = new ReentrantLock();
    Account(int acctNum, int balance){
        this.acctNum = acctNum;
        this.balance = balance;
    }

    /**
     * Method for depositing amount
     * @param amount
     * @return
     */
    public boolean deposit(int amount){
        System.out.println("In deposit method");
        if(this.lock.tryLock()){
            try {
                // Simulating some delay
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("deposit in " + this.acctNum + " for " 
              + Thread.currentThread().getName());
            this.balance = balance + amount;
            return true;
        }
        return false;
    }

    /**
     * Method for withdrawing amount
     * @param amount
     * @return
     */
    public boolean withdraw(int amount){
        System.out.println("In withdraw method");
        if(this.lock.tryLock()){
            try {
                // Simulating some delay
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("Withdrawn from " + this.acctNum + " for " 
              + Thread.currentThread().getName());
            this.balance = balance - amount;
            return true;
        }
        return false;
    }

    public boolean transact(Account targetAcct, int amount){
        //System.out.println("In transact method " + targetAcct);
        boolean flag = false;
        // If you can withdraw from the source account and
        // deposit it into target account then only return true        
        if(this.withdraw(amount) && targetAcct.deposit(amount)){
                flag = true;
        }else{
            // Rollback and deposit the withdrawn amount back in source account    
            System.out.println("Failed to deposit in " + targetAcct.acctNum + 
              " depositing back in account " + this.acctNum);
            this.deposit(amount);

        }
        return flag;
    }
}

class Operation implements Runnable{
    Account sourceAccount;
    Account targetAccount;
    int amount;
    Operation(Account sourceAccount, Account targetAccount, int amount){
        this.sourceAccount = sourceAccount;
        this.targetAccount = targetAccount;
        this.amount = amount;
    }

    @Override
    public void run() {
 while(!sourceAccount.transact(targetAccount, amount)){
  continue;
  } 
 }
}

Output livelock

References https://netjs.blogspot.my/2017/12/livelock-in-java-multi-threading.html

ZmahHata commented 6 years ago

CODE

package mylivelock;

import java.util.LinkedList;

public class MyLivelock {

    public static void main(String[] args) {
        LinkedList<Equation> queue = new LinkedList<Equation>();
        Thread t1 = new Thread(new Reader(queue), "Thread_1_P10");
        Thread t2 = new Thread(new Reader(queue), "Thread_2_P10");
        t1.start();
        t2.start();
        queue.add(new Equation(100, 5));
        queue.add(new Equation(120, 6));
        queue.add(new Equation(101, 3));
        queue.add(new Equation(1024, 62));
        queue.add(new Equation(1892090, 53));
        queue.add(new Equation(72, 8));
        queue.add(new Equation(198, 0));
        queue.add(new Equation(123, 23));
        queue.add(new Equation(98495, 876));
    }

    private static class Reader implements Runnable {

        LinkedList<Equation> queue = null;

        public Reader(LinkedList<Equation> queue) {
            this.queue = queue;
        }

        public void run() {
            while (true) {
                synchronized (queue) {
                    System.out.format("%s Checking elements in the queue...\n", Thread.currentThread().getName());
                    try {
                        if (queue.size() > 0) {
                            Equation eq = queue.remove(0);
                            doWork(eq);
                            queue.wait(200);
                        }
                        Thread.sleep(1000);
                        queue.notify();
                    } catch (InterruptedException e) {
                        System.out.format("%s was interrupted...\n", Thread.currentThread().getName());
                        e.printStackTrace();
                    }
                }
            }
        }

        private void doWork(Equation eq) {
            double val = 0;
            try {
                val = (eq.getDividend() / eq.getDivisor());
                System.out.format("%s: Equation %d / %d = %f\n", Thread.currentThread().getName(), eq.getDividend(), eq.getDivisor(), val);
            } catch (ArithmeticException ex) {
                ex.printStackTrace();
                queue.addFirst(eq);
            }
        }
    }

    private static class Equation {

        private int dividend;
        private int divisor;

        public Equation(int dividend, int divisor) {
            setDividend(dividend);
            setDivisor(divisor);
        }

        public int getDividend() {
            return dividend;
        }

        public void setDividend(int dividend) {
            this.dividend = dividend;
        }

        public int getDivisor() {
            return divisor;
        }

        public void setDivisor(int divisor) {
            this.divisor = divisor;
        }
    }
}

OUTPUT image REFERENCE https://avaldes.com/java-thread-starvation-livelock-with-examples/

saufisyafiq commented 6 years ago

Source code

Test class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package livelock;

/**
 *
 * @author master lab
 */
public class Test {
    static final Police police = new Police();

    static final Criminal criminal = new Criminal();

    public static void main(String[] args) {

        Thread t1 = new Thread(new Runnable() {
            public void run() {
                police.giveRansom(criminal);
            }
        });
        t1.start();

        Thread t2 = new Thread(new Runnable() {
            public void run() {
                criminal.releaseHostage(police);
            }
        });
        t2.start();
    }

}

Police class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package livelock;

/**
 *
 * @author master lab
 */
public class Police {
    private boolean moneySent = false;

    public void giveRansom(Criminal criminal) {

        while (!criminal.isHostageReleased()) {

            System.out.println("Police: waiting criminal to release hostage");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }

        System.out.println("Police: sent money");

        this.moneySent = true;
    }

    public boolean isMoneySent() {
        return this.moneySent;
    }
}

Criminal class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package livelock;

/**
 *
 * @author master lab
 */
public class Criminal {

    private boolean hostageReleased = false;

    public void releaseHostage(Police police) {
        while (!police.isMoneySent()) {

            System.out.println("Criminal: waiting police to give ransom");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }

        System.out.println("Criminal: released hostage");

        this.hostageReleased = true;
    }

    public boolean isHostageReleased() {
        return this.hostageReleased;
    }

}

Output capture1

diyanazaidi commented 6 years ago

Main class


package issue13;

public class Issue13 {

    static final Lecturer lecturer = new Lecturer();

    static final Student student = new Student();
    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                lecturer.giveRansom(student);
            }
        });
        t1.start();

        Thread t2 = new Thread(new Runnable() {
            public void run() {
                student.releaseHostage(lecturer);
            }
        });
        t2.start();
    }

}

Lecturer


package issue13;

public class Lecturer {
    private boolean moneySent = false;

    public void giveRansom(Student student) {

        while (!student.isHostageReleased()) {

            System.out.println("Lecturer: waiting student to start lecture");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }

        System.out.println("Lecturer: enter class");

        this.moneySent = true;
    }

    public boolean isMoneySent() {
        return this.moneySent;
    }
}

Student.java


package issue13;

public class Student {
    private boolean hostageReleased = false;

    public void releaseHostage(Lecturer lecturer) {
        while (!lecturer.isMoneySent()) {

            System.out.println("Student: waiting lecturer to start class");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }

        System.out.println("Student: Enter class");

        this.hostageReleased = true;
    }

    public boolean isHostageReleased() {
        return this.hostageReleased;
    }
}

output image

Reference : http://www.codejava.net/java-core/concurrency/understanding-deadlock-livelock-and-starvation-with-code-examples-in-java

Nurzyra commented 6 years ago

package issue.pkg13.livelock;

public class Issue13Livelock {

    public static void main(String[] args) throws InterruptedException {
        Object left = new Object();
        Object right = new Object();
        Pedestrian one = new Pedestrian(left, right, 0);
        Pedestrian two = new Pedestrian(right, left, 1); 
        one.setOther(two);
        two.setOther(one);
        one.start();
        two.start();
    }
}

class Pedestrian extends Thread {
    private Object l;
    private Object r;
    private Pedestrian other;
    private Object current;

    Pedestrian (Object left, Object right, int firstDirection) {
        l = left;
        r = right;
        if (firstDirection==0) {
            current = l;
        }
        else {
            current = r;
        }
    }

    void setOther(Pedestrian otherP) {
        other = otherP;
    }

    Object getDirection() {
        return current;
    }

    Object getOppositeDirection() {
        if (current.equals(l)) {
            return r;
        }
        else {
            return l;
        }
    }

    void switchDirection() throws InterruptedException {
        Thread.sleep(100);
        current = getOppositeDirection();
        System.out.println(Thread.currentThread().getName() + " is stepping aside.");
    }

    public void run() {
        while (getDirection().equals(other.getDirection())) {
            try {
                switchDirection();
                Thread.sleep(100);
            } catch (InterruptedException e) {}
        }
    }
} 

2

AdlanShahjehan commented 6 years ago
public class Exercise12 {

    public static void main(String[] args) {

        final Member member1 = new Member("Adlan ", true);
        final Member member2 = new Member("Anias", true);

        final CommonResource s = new CommonResource(member1);

        new Thread(() -> {
            member1.give(s, member2);
        }).start();

        new Thread(() -> {
            member2.give(s, member1);
        }).start();
    }
}

class CommonResource {

    private Member owner;

    public CommonResource(Member d) {
        member = d;
    }

    public Member getMember() {
        return member;
    }

    public synchronized void setMember(Member d) {
        member = d;
    }
}

class Member {

    private String name;
    private boolean active;

    public Member(String name, boolean active) {
        this.name = name;
        this.active = active;
    }

    public String getName() {
        return name;
    }

    public boolean isActive() {
        return active;
    }

    public synchronized void give(CommonResource commonResource, Member otherMember) {
        while (active) {

            if (commonResource.getMember() != this) {
                try {
                    wait(10);
                } catch (InterruptedException e) {
                    //ignore
                }
                continue;
            }

            if (otherMember.isActive()) {
                System.out.println(getName() + " : handing food to the member : "
                        + otherMember.getName());
                commonResource.setMember(otherMember);
                continue;
            }

            System.out.println(getName() + ": eating the common food");
            active = false;
            commonResource.setMember(otherMember);
        }
    }
}

Output screen shot 2018-04-22 at 12 18 39 pm

alifhaikal commented 6 years ago

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.issue13;

/**
 *
 * @author Alif Haikal
 */
public class Issue13 {

    static class Ball {

        private Game owner;

        public Ball(Game d) {
            owner = d;
        }

        public Game getOwner() {
            return owner;
        }

        public synchronized void setOwner(Game d) {
            owner = d;
        }

        public synchronized void play() {
            System.out.printf("%s has played!", owner.name);
        }
    }

    static class Game {

        private String name;
        private boolean isPlay;

        public Game(String n) {
            name = n;
            isPlay = true;
        }

        public String getName() {
            return name;
        }

        public boolean isPlay() {
            return isPlay;
        }

        public void playWith(Ball ball, Game friend) {
            while (isPlay) {

                if (ball.owner != this) {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        continue;
                    }
                    continue;
                }

                if (friend.isPlay()) {
                    System.out.printf(
                            "%s: You play first my friend %s!%n",
                            name, friend.getName());
                    ball.setOwner(friend);
                    continue;
                }

                ball.play();
                isPlay = false;
                System.out.printf(
                        "%s: I am tired, my friend %s!%n",
                        name, friend.getName());
                ball.setOwner(friend);
            }
        }
    }

    public static void main(String[] args) {
        final Game name1 = new Game("Ali");
        final Game name2 = new Game("Abu");

        final Ball s = new Ball(name1);

        new Thread(new Runnable() {
            public void run() {
                name1.playWith(s, name2);
            }
        }).start();

        new Thread(new Runnable() {
            public void run() {
                name2.playWith(s, name1);
            }
        }).start();
    }
}

issue13

syaba314 commented 6 years ago
package com.mycompany.issue12;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class issue12
{
    public static void main(String[] args)
    {
        Lock p = new ReentrantLock();
        Lock n = new ReentrantLock();
        Thread t1 = new Thread(new One(p,n));
        Thread t2 = new Thread(new Two(n,p));
        t1.start();
        t2.start();
    }
}

class One implements Runnable
{
    Lock p;
    Lock n;
    public One(Lock p, Lock n)
    {
        this.p = p;
        this.n = n;
    }
    public void run()
    {
        for(int i=0; i<1000; i++)
        {
            synchronized(p)
            {
                while(Thread.holdsLock(n))
                {
                    try {
                    p.unlock();
                    wait(10);
                    p.lock();
                    }catch(InterruptedException e){}
                }
                synchronized(n)
                {
                    System.out.println("RealTime");
                }
            }
        }
    }
}

class Two implements Runnable
{
    Lock p;
    Lock n;
    public Two(Lock n, Lock p)
    {
        this.p = p;
        this.n = n;
    }
    public void run()
    {
        for(int i=0; i<1000; i++)
        {
            synchronized(n)
            {
                while(Thread.holdsLock(p))
                {
                    try{
                    n.lock();
                    wait(10);
                    n.unlock();
                    }catch(InterruptedException e){}
                }
                synchronized(p)
                {
                    System.out.println("TimeReal");
                }
            }
        }
    }
}
23
thilagan7 commented 6 years ago
package livelock;

/**
 *
 * @author esp
 */
public class Livelock {

    static class Spoon {
        private Diner owner;
        public Spoon(Diner d) { owner = d; }
        public Diner getOwner() { return owner; }
        public synchronized void setOwner(Diner d) { owner = d; }
        public synchronized void use() { 
            System.out.printf("%s has eaten!", owner.name); 
        }
    }

    static class Diner {
        private String name;
        private boolean isHungry;

        public Diner(String n) { name = n; isHungry = true; }       
        public String getName() { return name; }
        public boolean isHungry() { return isHungry; }

        public void eatWith(Spoon spoon, Diner spouse) {
            while (isHungry) {
                // Don't have the spoon, so wait patiently for spouse.
                if (spoon.owner != this) {
                    try { Thread.sleep(1); } 
                    catch(InterruptedException e) { continue; }
                    continue;
                }                       

                // If spouse is hungry, insist upon passing the spoon.
                if (spouse.isHungry()) {                    
                    System.out.printf(
                        "%s: You eat first my dear %s!%n", 
                        name, spouse.getName());
                    spoon.setOwner(spouse);
                    continue;
                }
                // Spouse wasn't hungry, so finally eat
                spoon.use();
                isHungry = false;               
                System.out.printf(
                    "%s: I am stuffed, my dear %s!%n", 
                    name, spouse.getName());                
                spoon.setOwner(spouse);
            }
        }
    }

    public static void main(String[] args) {
        final Diner husband = new Diner("Johnson");
        final Diner wife = new Diner("Mia");

        final Spoon s1 = new Spoon(husband);

        new Thread(new Runnable() { 
            public void run() { husband.eatWith(s1, wife); }   
        }).start();

        new Thread(new Runnable() { 
            public void run() { wife.eatWith(s1, husband); } 
        }).start();
    }
}

untitled21

rubenmuhajir commented 6 years ago
package com.mycompany.livelock;

/**
 *
 * @author USER
 */
public class livelock {

      static class Spoon {
        private Diner owner;
        public Spoon(Diner d) { owner = d; }
        public Diner getOwner() { return owner; }
        public synchronized void setOwner(Diner d) { owner = d; }
        public synchronized void use() { 
            System.out.printf("%s has eaten!", owner.name); 
        }
    }

    static class Diner {
        private String name;
        private boolean isHungry;

        public Diner(String n) { name = n; isHungry = true; }       
        public String getName() { return name; }
        public boolean isHungry() { return isHungry; }

        public void eatWith(Spoon spoon, Diner s) {
            while (isHungry) {
                // Don't have the spoon, so wait patiently for s.
                if (spoon.owner != this) {
                    try { Thread.sleep(1); } 
                    catch(InterruptedException e) { continue; }
                    continue;
                }                       

                // If s is hungry, insist upon passing the spoon.
                if (s.isHungry()) {                    
                    System.out.printf(
                        "%s: Before you going out, eat first %s!%n", 
                        name, s.getName());
                    spoon.setOwner(s);
                    continue;
                }

                // Spouse wasn't hungry, so finally eat
                spoon.use();
                isHungry = false;               
                System.out.printf(
                    "%s: I'm not hungry, %s!%n", 
                    name, spouse.getName());                
                spoon.setOwner(s);
            }
        }
    }

    public static void main(String[] args) {
        final Diner son = new Diner("Navas");
        final Diner mother = new Diner("Mom");

        final Spoon s = new Spoon(son);

        new Thread(new Runnable() { 
            public void run() { son.eatWith(s, mother); }   
        }).start();

        new Thread(new Runnable() { 
            public void run() { mother.eatWith(s, son); } 
        }).start();
    }
}

untitled

https://stackoverflow.com/questions/1036364/good-example-of-livelock

thiviya commented 6 years ago
package execise12;
public class CommonResource {
    private Worker owner;

    public CommonResource (Worker d) {
        owner = d;
    }

    public Worker getOwner () {
        return owner;
    }

    public synchronized void setOwner (Worker d) {
        owner = d;
    }
}
package execise12;
public class Worker {
    private String name;
    private boolean active;

    public Worker (String name, boolean active) {
        this.name = name;
        this.active = active;
    }

    public String getName () {
        return name;
    }

    public boolean isActive () {
        return active;
    }

    public synchronized void work (CommonResource commonResource, Worker otherWorker) {
        while (active) {
            // wait for the resource to become available.
            if (commonResource.getOwner() != this) {
                try {
                    wait(10);
                } catch (InterruptedException e) {
                   //ignore
                }
                continue;
            }

            // If other worker is also active let it do it's work first
            if (otherWorker.isActive()) {
                System.out.println(getName() +
                            " : handover the resource to the worker " +
                                                       otherWorker.getName());
                commonResource.setOwner(otherWorker);
                continue;
            }

            //now use the commonResource
            System.out.println(getName() + ": working on the common resource");
            active = false;
            commonResource.setOwner(otherWorker);
        }
    }
}
package execise12;
public class Livelock {

    public static void main (String[] args) {
        final Worker worker1 = new Worker("Worker 1 ", true);
        final Worker worker2 = new Worker("Worker 2", true);

        final CommonResource s = new CommonResource(worker1);

        new Thread(() -> {
            worker1.work(s, worker2);
        }).start();

        new Thread(() -> {
            worker2.work(s, worker1);
        }).start();
    }
}

image

adamrustam commented 6 years ago

Source code


import static java.lang.System.out;

public class Livelock {

    public static void main(String[] args) {
        Spoon spoon = new Spoon();
        Dish dish = new Dish();

        new Thread(new Husband(spoon, dish)).start();
        new Thread(new Wife(spoon, dish)).start();
    }
}

class Spoon {
    boolean isLocked;
}

class Dish {
    boolean isLocked;
}

class Husband implements Runnable {

    Spoon spoon;
    Dish dish;

    Husband(Spoon spoon, Dish dish) {
        this.spoon = spoon;
        this.dish = dish;
    }

    @Override
    public void run() {

        while (true) {
            synchronized (spoon) {
                spoon.isLocked = true;
                out.println("husband get spoon");
                try { Thread.sleep(2000); } catch (InterruptedException e) {}

                if (dish.isLocked == true) {
                    spoon.isLocked = false; // give away spoon
                    out.println("husband pass away spoon");
                    continue;
                }
                synchronized (dish) {
                    dish.isLocked = true;
                    out.println("Husband is eating!");

                }
                dish.isLocked = false;
            }
            spoon.isLocked = false;
        }
    }
}

class Wife implements Runnable {

    Spoon spoon;
    Dish dish;

    Wife(Spoon spoon, Dish dish) {
        this.spoon = spoon;
        this.dish = dish;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (dish) {
                dish.isLocked = true;
                out.println("wife get dish");
                try { Thread.sleep(2000); } catch (InterruptedException e) {}

                if (spoon.isLocked == true) {
                    dish.isLocked = false; // give away dish
                    out.println("wife pass away dish");
                    continue;
                }
                synchronized (spoon) {
                    spoon.isLocked = true;
                    out.println("Wife is eating!");

                }
                spoon.isLocked = false;
            }
            dish.isLocked = false;
        }
    }
}

Output

screen shot 2018-04-22 at 1 43 01 pm

References

https://www.logicbig.com/tutorials/core-java-tutorial/java-multi-threading/thread-livelock.html https://stackoverflow.com/questions/1036364/good-example-of-livelock?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

ghost commented 6 years ago

Source Code

Here's a very simple Java example of livelock where a husband and wife are trying to eat soup, but only have one spoon between them. Each spouse is too polite, and will pass the spoon if the other has not yet eaten.

public class Livelock {
    static class Spoon {
        private Diner owner;
        public Spoon(Diner d) { owner = d; }
        public Diner getOwner() { return owner; }
        public synchronized void setOwner(Diner d) { owner = d; }
        public synchronized void use() { 
            System.out.printf("%s has eaten!", owner.name); 
        }
    }

    static class Diner {
        private String name;
        private boolean isHungry;

        public Diner(String n) { name = n; isHungry = true; }       
        public String getName() { return name; }
        public boolean isHungry() { return isHungry; }

        public void eatWith(Spoon spoon, Diner spouse) {
            while (isHungry) {
                // Don't have the spoon, so wait patiently for spouse.
                if (spoon.owner != this) {
                    try { Thread.sleep(1); } 
                    catch(InterruptedException e) { continue; }
                    continue;
                }                       

                // If spouse is hungry, insist upon passing the spoon.
                if (spouse.isHungry()) {                    
                    System.out.printf(
                        "%s: You eat first my darling %s!%n", 
                        name, spouse.getName());
                    spoon.setOwner(spouse);
                    continue;
                }

                // Spouse wasn't hungry, so finally eat
                spoon.use();
                isHungry = false;               
                System.out.printf(
                    "%s: I am stuffed, my darling %s!%n", 
                    name, spouse.getName());                
                spoon.setOwner(spouse);
            }
        }
    }

    public static void main(String[] args) {
        final Diner husband = new Diner("Bob");
        final Diner wife = new Diner("Alice");

        final Spoon s = new Spoon(husband);

        new Thread(new Runnable() { 
            public void run() { husband.eatWith(s, wife); }   
        }).start();

        new Thread(new Runnable() { 
            public void run() { wife.eatWith(s, husband); } 
        }).start();
    }
}

Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif! Alif: You eat first my darling Rosya! Rosya: You eat first my darling Alif!

umarabdullah commented 6 years ago
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package issues;

/**
 *
 * @author abdullah
 */
public class Issue17 {

    /**
     * @param args the command line arguments
     */
    static final Person1 p1 = new Person1();

    static final Person2 p2 = new Person2();

    public static void main(String[] args) {

        Thread t1 = new Thread(new Runnable() {
            public void run() {
                p2.admitTofault(p1);
            }
        });
        t1.start();

        Thread t2 = new Thread(new Runnable() {
            public void run() {
                p1.forgivePerson(p2);
            }
        });
        t2.start();
    }

}
class Person1 {
    private boolean forgive = false;
    private String name = "Kate Becket";

    public void forgivePerson (Person2 person) {

        while (!person.isapologise()) {

            System.out.println( this.name + " waiting for apology ");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }

        System.out.println(this.name + ": forgive " + person.getName());

        this.forgive = true;
    }

    public String getName() {
        return name;
    }

    public boolean isforgive() {
        return this.forgive;
    }

}

class Person2 {
    private boolean apologise = false;
    private String name = "Richard Castle";
    public void admitTofault(Person1 person) {
        while (!person.isforgive()) {

            System.out.println( this.name + " waiting for forgiveness");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }

        System.out.println(this.name + ": admit to the fault and apologise");

        this.apologise = true;
    }
     public String getName() {
        return name;
    }
    public boolean isapologise() {
        return this.apologise;
    }
}

Person2 is an egoistic person who is at fault but does not want to apologise and he waits for forgiveness from person1. Person1 on the other hand waits for person2 to admit his fault and apologise before she can forgive him. Both are waiting for each other to act first, hence livelock.

screen shot 2018-05-24 at 3 02 53 am