The simplest method is to make your variables private (but you do that already,  right?) and to use synchronized accessor methods. Accessor methods allow access to private member variables, but in a controlled manner. Take the following accessor methods, which provide a safe way to change the value of a counter.

 

public class MyCounter{

    private int count = 0; // count starts at zero

     public synchronized void setCount(int amount)

    {

        count = amount;

    }

   

    public synchronized int getCount()

    {

        return count;

    }

}