我应该使用原子整数还是同步

时间:2018-12-14 08:45:49

标签: java multithreading concurrency synchronization atomic

我对在代码中使用atomic / volatile / sync感到有些困惑。 假设我在一家书店中有一个图书信息对象,例如,有可能两个线程想要取同一本书,而库存中的数量仅为1,我如何保证只有一个线程可以取这本书? 我必须使用同步吗? BookInventoryInfo:

package bgu.spl.mics.application.passiveObjects;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Passive data-object representing a information about a certain book in the inventory.
 * 
 * <p>
 *
 */
public class BookInventoryInfo {

    //The title of the book, his amount in the inventory and the price
    private String bookTitle;
    private AtomicInteger amountInInventory;
    private int price;

    public BookInventoryInfo(String bookTitle, int amountInInventory, int price) {
        this.bookTitle = bookTitle;
        this.price = price;
        this.amountInInventory = new AtomicInteger(amountInInventory);
    }


    /**
     * Retrieves the title of this book.
     * <p>
     * @return The title of this book.   
     */
    public String getBookTitle() {
        return this.bookTitle;
    }

    /**
     * Retrieves the amount of books of this type in the inventory.
     * <p>
     * @return amount of available books.      
     */
    public int getAmountInInventory() {
        return this.amountInInventory.get();
    }

    /**
     * Retrieves the price for  book.
     * <p>
     * @return the price of the book.
     */
    public int getPrice() {
        return this.price;
    }

    public void reduceAmountInInventory() {
        this.amountInInventory.decrementAndGet();
    }
}

我想拿这本书的方式:

if(book.getAmountInInventory > 0)
{
    book.amountInInventory--
}

3 个答案:

答案 0 :(得分:5)

您应该使用synchronized,因为使用AtomicInteger并不像乍看起来那样简单。尽管AtomicInteger上的单个操作是线程安全的,但使用多个操作可能不是安全的。您的例子是一个很好的例子。说你有

// say it start at 1
Thread1: if(book.getAmountInInventory > 0)
Thread2: if(book.getAmountInInventory > 0)
Thread1: book.amountInInventory--
Thread2: book.amountInInventory--

金额现在为-1。

如果您使用synchronized,则在整个操作过程中持有锁要简单得多

synchronized (book) {
    if(book.getAmountInInventory > 0) // no chance for a race condition here.
    {
        book.amountInInventory--
    }

答案 1 :(得分:3)

AtomicInteger在这里还不够。尽管它可以让您原子地减少清单中的副本数,但这还不够-您不需要仅原子地减少副本数,还需要添加一些自定义逻辑。

我将使用普通的旧int,并使用显式synchronized块或方法保护其修改:

public class BookInventoryInfo {

    private String bookTitle;
    private int amountInInventory;
    private int price;

    public synchronized void checkOut() {
        if (amountInInventory <= 0) {
            throw new BookCheckoutException("No book in inventory");
        }
        amountInInventory--;
    }

    // All the other methods...
}

答案 2 :(得分:3)

作为同步的替代方法,您还可以使用compareAndSet

int a = book.amountInventory.get();
if (a > 0) {
  boolean updated = book.amountInInventory.compareAndSet(a, a - 1);
}

如果您要更新amountInInventory的值仍为a,则这将仅 递减。返回值compareAndSet指示该值是否已更改。

您可以将其包装成一个循环,例如:

while (true) {
  int a = book.amountInventory.get();
  if (a == 0) {
    return false;  // To mean "no book in inventory";
  }
  if (book.amountInInventory.compareAndSet(a, a - 1)) {
    return true;  // To mean "there was a book in inventory, and it was removed".
  }
}