Java - Thread safe program

Viewed 856

Consider the following piece of code:

public class Test
    {
        private List<Object> list;

        public Object get(int id)
        {
            return list.get(id);
        }

        public void add(Object el)
        {
            list.add(el);
        }

        public List<Object> getList()
        {
            return list;
        }
    }

I have to make sure that it is thread safe (there will be no synchronization errors). I am pretty new to this thing, so my guesses are:

  1. We add synchronized to the add() and get() methods and we add synchronized(Test.class) to the getList() method;

  2. We make list static and all the methods static, then we add synchronized;

This is what I came up with, it's possible that neither of them are right though.

5 Answers

That piece of code is thread safe already. Why ? because the global variable is non-static variable. All the thread will create it's own variable List<Object> list; Except if you make List<Object> list; to be a static variable.

Related