ライブロックとは何なのかは理解していますが、コードベースの良い例を誰かが持っているのではないかと思いました。また、コードベースで言うと、「廊下で2人がお互いを乗り越えようとしている」という意味ではありません。それをもう一度読んだら、昼食を失うだろう。
ライブロックとは何なのかは理解していますが、コードベースの良い例を誰かが持っているのではないかと思いました。また、コードベースで言うと、「廊下で2人がお互いを乗り越えようとしている」という意味ではありません。それをもう一度読んだら、昼食を失うだろう。
回答:
これは、夫と妻がスープを食べようとしているが、間にスプーンが1つしかない、非常に単純なJavaのライブロックの例です。各配偶者は礼儀正しく、他の配偶者がまだ食べていない場合はスプーンを通過します。
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();
    }
}getOwnerメソッドも同期する必要はありませんか?効果的なJavaから「読み取りと書き込みの両方を行わない限り、同期は効果がありません」。
                    Thread.join()ではなくを使用するべきではありませんThread.sleep()か?
                    getOwner場合でも、以降の方法は、同期している必要がありますsetOwner同期され、これは使用してスレッドを保証するものではありませんgetOwner(またはフィールドにアクセスしてowner実行する他のスレッドによって行われた変更を見ることができます直接)setOwner。このvidはこれを非常に注意深く説明しています:youtube.com/watch
                    synchronized 、setOwnermethodにキーワードを使用する必要はありません。
                    軽快なコメントは別として、浮かび上がることがわかっている1つの例は、デッドロック状態を検出して処理しようとするコードです。2つのスレッドがデッドロックを検出し、お互いに「脇に」移動しようとすると、注意せずにループが常に「脇に」ループし、先に進むことができなくなります。
「一歩脇に」とは、ロックを解除して、もう一方にロックを獲得させようとすることを意味します。2つのスレッドがこれを実行している状況(疑似コード)を想像するかもしれません。
// thread 1
getLocks12(lock1, lock2)
{
  lock1.lock();
  while (lock2.locked())
  {
    // attempt to step aside for the other thread
    lock1.unlock();
    wait();
    lock1.lock();
  }
  lock2.lock();
}
// thread 2
getLocks21(lock1, lock2)
{
  lock2.lock();
  while (lock1.locked())
  {
    // attempt to step aside for the other thread
    lock2.unlock();
    wait();
    lock2.lock();
  }
  lock1.lock();
}
競合状態はさておき、ここにあるのは、両方のスレッドが同時に入ると、処理を続行せずに内部ループで実行されてしまう状況です。明らかにこれは単純化された例です。素朴な修正は、スレッドが待機する時間の量にある種のランダムさを入れることです。
適切な修正は、常にロック階層を尊重することです。ロックを取得する順序を選択し、それに固執します。たとえば、両方のスレッドが常にlock2の前にlock1を取得する場合、デッドロックの可能性はありません。
受け入れられた回答としてマークされた回答がないため、ライブロックの例を作成しようとしました。
オリジナルのプログラムは、2012年4月にマルチスレッドのさまざまな概念を学ぶために私が作成しました。今回はデッドロック、競合状態、ライブロックなどを作成するように変更しました。
まず、問題の説明を理解しましょう。
クッキーメーカーの問題
いくつかの成分コンテナがあります:ChocoPowederContainer、WheatPowderContainer。CookieMakerは、原料容器からある程度の量の粉末を取り、Cookieを焼きますます。cookieメーカーは、空のコンテナを見つけると、別のコンテナをチェックして時間を節約します。そして、フィラーが必要なコンテナを満たすまで待ちます。定期的にコンテナをチェックし、コンテナがそれを必要とする場合、一定量を充填するフィラーがあります。
githubで完全なコードを確認してください。
実装について簡単に説明しましょう。
コードを見てみましょう:
CookieMaker.java
private Integer getMaterial(final Ingredient ingredient) throws Exception{
        :
        container.lock();
        while (!container.getIngredient(quantity)) {
            container.empty.await(1000, TimeUnit.MILLISECONDS);
            //Thread.sleep(500); //For deadlock
        }
        container.unlock();
        :
}
IngredientContainer.java
public boolean getIngredient(int n) throws Exception {
    :
    lock();
    if (quantityHeld >= n) {
        TimeUnit.SECONDS.sleep(2);
        quantityHeld -= n;
        unlock();
        return true;
    }
    unlock();
    return false;
}
フィラーまですべてうまくいきますがコンテナーを満たすれます。しかし、フィラーを開始するのを忘れた場合、またはフィラーが予期しない休暇をとった場合、サブスレッドは状態を変更し続け、他のメーカーがコンテナをチェックできるようにします。
また、スレッドの状態とデッドロックを監視するThreadTracerデーモンを作成しました。これはコンソールからの出力です。
2016-09-12 21:31:45.065 :: [Maker_0:WAITING, Maker_1:WAITING, Maker_2:WAITING, Maker_3:WAITING, Maker_4:WAITING, Maker_5:WAITING, Maker_6:WAITING, Maker_7:WAITING, pool-7-thread-1:TIMED_WAITING, pool-7-thread-2:TIMED_WAITING, pool-8-thread-1:TIMED_WAITING, pool-8-thread-2:TIMED_WAITING, pool-6-thread-1:TIMED_WAITING, pool-6-thread-2:TIMED_WAITING, pool-5-thread-1:TIMED_WAITING, pool-5-thread-2:TIMED_WAITING, pool-1-thread-1:TIMED_WAITING, pool-3-thread-1:TIMED_WAITING, pool-2-thread-1:TIMED_WAITING, pool-1-thread-2:TIMED_WAITING, pool-4-thread-1:TIMED_WAITING, pool-4-thread-2:RUNNABLE, pool-3-thread-2:TIMED_WAITING, pool-2-thread-2:TIMED_WAITING]
2016-09-12 21:31:45.065 :: [Maker_0:WAITING, Maker_1:WAITING, Maker_2:WAITING, Maker_3:WAITING, Maker_4:WAITING, Maker_5:WAITING, Maker_6:WAITING, Maker_7:WAITING, pool-7-thread-1:TIMED_WAITING, pool-7-thread-2:TIMED_WAITING, pool-8-thread-1:TIMED_WAITING, pool-8-thread-2:TIMED_WAITING, pool-6-thread-1:TIMED_WAITING, pool-6-thread-2:TIMED_WAITING, pool-5-thread-1:TIMED_WAITING, pool-5-thread-2:TIMED_WAITING, pool-1-thread-1:TIMED_WAITING, pool-3-thread-1:TIMED_WAITING, pool-2-thread-1:TIMED_WAITING, pool-1-thread-2:TIMED_WAITING, pool-4-thread-1:TIMED_WAITING, pool-4-thread-2:TIMED_WAITING, pool-3-thread-2:TIMED_WAITING, pool-2-thread-2:TIMED_WAITING]
WheatPowder Container has 0 only.
2016-09-12 21:31:45.082 :: [Maker_0:WAITING, Maker_1:WAITING, Maker_2:WAITING, Maker_3:WAITING, Maker_4:WAITING, Maker_5:WAITING, Maker_6:WAITING, Maker_7:WAITING, pool-7-thread-1:TIMED_WAITING, pool-7-thread-2:TIMED_WAITING, pool-8-thread-1:TIMED_WAITING, pool-8-thread-2:TIMED_WAITING, pool-6-thread-1:TIMED_WAITING, pool-6-thread-2:TIMED_WAITING, pool-5-thread-1:TIMED_WAITING, pool-5-thread-2:TIMED_WAITING, pool-1-thread-1:TIMED_WAITING, pool-3-thread-1:TIMED_WAITING, pool-2-thread-1:TIMED_WAITING, pool-1-thread-2:TIMED_WAITING, pool-4-thread-1:TIMED_WAITING, pool-4-thread-2:TIMED_WAITING, pool-3-thread-2:TIMED_WAITING, pool-2-thread-2:RUNNABLE]
2016-09-12 21:31:45.082 :: [Maker_0:WAITING, Maker_1:WAITING, Maker_2:WAITING, Maker_3:WAITING, Maker_4:WAITING, Maker_5:WAITING, Maker_6:WAITING, Maker_7:WAITING, pool-7-thread-1:TIMED_WAITING, pool-7-thread-2:TIMED_WAITING, pool-8-thread-1:TIMED_WAITING, pool-8-thread-2:TIMED_WAITING, pool-6-thread-1:TIMED_WAITING, pool-6-thread-2:TIMED_WAITING, pool-5-thread-1:TIMED_WAITING, pool-5-thread-2:TIMED_WAITING, pool-1-thread-1:TIMED_WAITING, pool-3-thread-1:TIMED_WAITING, pool-2-thread-1:TIMED_WAITING, pool-1-thread-2:TIMED_WAITING, pool-4-thread-1:TIMED_WAITING, pool-4-thread-2:TIMED_WAITING, pool-3-thread-2:TIMED_WAITING, pool-2-thread-2:TIMED_WAITING]
そのサブスレッドとその状態の変更と待機に気付くでしょう。
実際の(正確なコードはありませんが)例は、SQLサーバーのデッドロックを修正するための2つの競合するプロセスのライブロックであり、各プロセスが同じ再試行の待機再試行アルゴリズムを使用しています。これはタイミングの運ですが、EMSトピックに追加されたメッセージ(たとえば、単一のオブジェクトグラフの更新を複数回保存する)に応答して同様のパフォーマンス特性を持つ別のマシンで発生し、制御できないことがわかりました。ロック順序。
この場合の適切な解決策は、競合するコンシューマーを使用することです(無関係なオブジェクトでの作業をパーティション化することにより、チェーン内の重複処理を可能な限り高くしないようにします)。
あまり望ましくない(OK、ダーティーハック)ソリューションは、タイミングの不運(処理における力の差のようなもの)を事前に解消するか、異なるアルゴリズムまたはランダム性のいくつかの要素を使用してデッドロック後にそれを解消することです。ロックの取得順序がプロセスごとに「スティッキー」であり、待機再試行で考慮されない特定の最小時間がかかるため、これにはまだ問題がある可能性があります。
さらに別の解決策(少なくともSQL Serverの場合)は、異なる分離レベル(スナップショットなど)を試すことです。
廊下を2人が通過する例をコード化しました。2つのスレッドは、方向が同じであることを認識するとすぐに互いを回避します。
public class LiveLock {
    public static void main(String[] args) throws InterruptedException {
        Object left = new Object();
        Object right = new Object();
        Pedestrian one = new Pedestrian(left, right, 0); //one's left is one's left
        Pedestrian two = new Pedestrian(right, left, 1); //one's left is two's right, so have to swap order
        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) {}
        }
    }
} 
jelbournのコードのC#バージョン:
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace LiveLockExample
{
    static class Program
    {
        public static void Main(string[] args)
        {
            var husband = new Diner("Bob");
            var wife = new Diner("Alice");
            var s = new Spoon(husband);
            Task.WaitAll(
                Task.Run(() => husband.EatWith(s, wife)),
                Task.Run(() => wife.EatWith(s, husband))
                );
        }
        public class Spoon
        {
            public Spoon(Diner diner)
            {
                Owner = diner;
            }
            public Diner Owner { get; private set; }
            [MethodImpl(MethodImplOptions.Synchronized)]
            public void SetOwner(Diner d) { Owner = d; }
            [MethodImpl(MethodImplOptions.Synchronized)]
            public void Use()
            {
                Console.WriteLine("{0} has eaten!", Owner.Name);
            }
        }
        public class Diner
        {
            public Diner(string n)
            {
                Name = n;
                IsHungry = true;
            }
            public string Name { get; private set; }
            private bool IsHungry { get; set; }
            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 (ThreadInterruptedException e)
                        {
                        }
                        continue;
                    }
                    // If spouse is hungry, insist upon passing the spoon.
                    if (spouse.IsHungry)
                    {
                        Console.WriteLine("{0}: You eat first my darling {1}!", Name, spouse.Name);
                        spoon.SetOwner(spouse);
                        continue;
                    }
                    // Spouse wasn't hungry, so finally eat
                    spoon.Use();
                    IsHungry = false;
                    Console.WriteLine("{0}: I am stuffed, my darling {1}!", Name, spouse.Name);
                    spoon.SetOwner(spouse);
                }
            }
        }
    }
}
ここでの1つの例は、時限tryLockを使用して複数のロックを取得することであり、それらをすべて取得できない場合は、元に戻して再試行してください。
boolean tryLockAll(Collection<Lock> locks) {
  boolean grabbedAllLocks = false;
  for(int i=0; i<locks.size(); i++) {
    Lock lock = locks.get(i);
    if(!lock.tryLock(5, TimeUnit.SECONDS)) {
      grabbedAllLocks = false;
      // undo the locks I already took in reverse order
      for(int j=i-1; j >= 0; j--) {
        lock.unlock();
      }
    }
  }
}
多くのスレッドが衝突し、ロックのセットを取得するために待機しているため、このようなコードは問題になると想像できます。しかし、これが簡単な例として私にとって非常に説得力があるかどうかはわかりません。
tryLockAll()ロックを使用する場合locks、ライブロックはありません。
                    jelbournのコードのPythonバージョン:
import threading
import time
lock = threading.Lock()
class Spoon:
    def __init__(self, diner):
        self.owner = diner
    def setOwner(self, diner):
        with lock:
            self.owner = diner
    def use(self):
        with lock:
            "{0} has eaten".format(self.owner)
class Diner:
    def __init__(self, name):
        self.name = name
        self.hungry = True
    def eatsWith(self, spoon, spouse):
        while(self.hungry):
            if self != spoon.owner:
                time.sleep(1) # blocks thread, not process
                continue
            if spouse.hungry:
                print "{0}: you eat first, {1}".format(self.name, spouse.name)
                spoon.setOwner(spouse)
                continue
            # Spouse was not hungry, eat
            spoon.use()
            print "{0}: I'm stuffed, {1}".format(self.name, spouse.name)
            spoon.setOwner(spouse)
def main():
    husband = Diner("Bob")
    wife = Diner("Alice")
    spoon = Spoon(husband)
    t0 = threading.Thread(target=husband.eatsWith, args=(spoon, wife))
    t1 = threading.Thread(target=wife.eatsWith, args=(spoon, husband))
    t0.start()
    t1.start()
    t0.join()
    t1.join()
if __name__ == "__main__":
    main()
@jelbournの答えを変更します。彼らのうちの1人が他の人がお腹が空いていることに気付いたら、スプーンを解放して別の通知を待つ必要があります。これにより、ライブロックが発生します。
public class LiveLock {
    static class Spoon {
        Diner owner;
        public String getOwnerName() {
            return owner.getName();
        }
        public void setOwner(Diner diner) {
            this.owner = diner;
        }
        public Spoon(Diner diner) {
            this.owner = diner;
        }
        public void use() {
            System.out.println(owner.getName() + " use this spoon and finish eat.");
        }
    }
    static class Diner {
        public Diner(boolean isHungry, String name) {
            this.isHungry = isHungry;
            this.name = name;
        }
        private boolean isHungry;
        private String name;
        public String getName() {
            return name;
        }
        public void eatWith(Diner spouse, Spoon sharedSpoon) {
            try {
                synchronized (sharedSpoon) {
                    while (isHungry) {
                        while (!sharedSpoon.getOwnerName().equals(name)) {
                            sharedSpoon.wait();
                            //System.out.println("sharedSpoon belongs to" + sharedSpoon.getOwnerName())
                        }
                        if (spouse.isHungry) {
                            System.out.println(spouse.getName() + "is hungry,I should give it to him(her).");
                            sharedSpoon.setOwner(spouse);
                            sharedSpoon.notifyAll();
                        } else {
                            sharedSpoon.use();
                            sharedSpoon.setOwner(spouse);
                            isHungry = false;
                        }
                        Thread.sleep(500);
                    }
                }
            } catch (InterruptedException e) {
                System.out.println(name + " is interrupted.");
            }
        }
    }
    public static void main(String[] args) {
        final Diner husband = new Diner(true, "husband");
        final Diner wife = new Diner(true, "wife");
        final Spoon sharedSpoon = new Spoon(wife);
        Thread h = new Thread() {
            @Override
            public void run() {
                husband.eatWith(wife, sharedSpoon);
            }
        };
        h.start();
        Thread w = new Thread() {
            @Override
            public void run() {
                wife.eatWith(husband, sharedSpoon);
            }
        };
        w.start();
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        h.interrupt();
        w.interrupt();
        try {
            h.join();
            w.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
package concurrently.deadlock;
import static java.lang.System.out;
/* This is an example of livelock */
public class Dinner {
    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;
        }
    }
}