user3636636
user3636636

Reputation: 2499

Incrementing Static variable with threads

I have a number of Customers each has its own thread. I have a cafe object which contains a semaphore with maximum of 5 permits. Customers arrive and leave at different times, so I need to keep track of time passed, a customer acquires a permit from the semaphore when it arrives and releases it when it leaves.

The customer implements runnable, which calls this below 'eat' method of the cafe. I have tested and my counter is being incremented above the arrival times, yet the try/ catch statement is not getting called.

public void eat(Customer customer)
{

    while(true) {

        System.out.println("hello");

        if (customer.getArrivalTime() < Main.counter) {

            try {

                semaphore.acquire();
                System.out.println(customer.getName() + ' ' + customer.getArrivalTime());
                TimeUnit.SECONDS.sleep(customer.getLeavetime());
            } catch (InterruptedException iex) {
                iex.printStackTrace();
            } finally {
                //System.out.printf("Farmer %s has crossed the bridge.\n",customer.getName());
                semaphore.release();
                System.out.println(Main.counter);
                break;
            }
        }
    }
}

Relevant snippet of Customer Class

public class Customer implements Runnable{

    public void run() {
            icecream.eat(this);

}

Relevant snippet of main

 public class Main {

    static int counter = 0;
    static Timer timer;

    public static void main(String[] args) {

    //create timer task to increment counter
        TimerTask timerTask = new TimerTask() {

        @Override
        public void run() {
            // System.out.println("TimerTask executing counter is: " + counter);
            counter++;
        }
    };

    Customer c1 = new Customer(Parlor, 5); //arrival time of 5
    Thread t1 = new Thread(c1);
    timer = new Timer("MyTimer");//create a new timer
    timer.scheduleAtFixedRate(timerTask, 1000, 1000); //start timer to increment  counter
    t1.start();

Any help would be appreciated

Upvotes: 0

Views: 1252

Answers (1)

Paul Wasilewski
Paul Wasilewski

Reputation: 10372

The changes of the counter variable are not visible to all threads. To make sure that all threads reading the same counter value you have to use volatile.

static volatile int counter = 0;

More information see Atomic Access and static vs. volatile.

Upvotes: 1

Related Questions