Is nested synchronized block necessary?

Posted by Dan on Stack Overflow See other posts from Stack Overflow or by Dan
Published on 2012-11-03T10:24:45Z Indexed on 2012/11/03 11:00 UTC
Read the original article Hit count: 256

Filed under:
|
|

I am writing a multithreaded program and I have a method that has a nested synchronized blocks and I was wondering if I need the inner sync or if just the outer sync is good enough.

public class Tester {

    private BlockingQueue<Ticket> q = new LinkedBlockingQueue<>();
    private ArrayList<Long> list = new ArrayList<>();

    public void acceptTicket(Ticket p) {
        try {
            synchronized (q) {
                q.put(p);

                synchronized (list) {
                    if (list.size() < 5) {
                        list.add(p.getSize());
                    } else {
                        list.remove(0);
                        list.add(p.getSize());
                        }
                }
            }
        } catch (InterruptedException ex) {
            Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

EDIT: This isn't a complete class as I am still working on it. But essentially I am trying to emulate a ticket machine. The ticket machine maintains a list of tickets in the BlockingQueue q. Whenever a client adds a ticket to the machine, the machine also keeps track of the price of the last 5 tickets (ArrayList list)

© Stack Overflow or respective owner

Related posts about java

Related posts about synchronization