synchronized in java - Proper use

Posted by ZoharYosef on Stack Overflow See other posts from Stack Overflow or by ZoharYosef
Published on 2014-06-09T21:01:08Z Indexed on 2014/06/09 21:24 UTC
Read the original article Hit count: 201

Filed under:
|
|

I'm building a simple program to use in multi processes (Threads).

My question is more to understand - when I have to use a reserved word synchronized?

Do I need to use this word in any method that affects the bone variables?

I know I can put it on any method that is not static, but I want to understand more.

thank you!

here is the code:

public class Container {
// *** data members ***
public static final int INIT_SIZE=10;  // the first (init) size of the set.
public static final int RESCALE=10;   // the re-scale factor of this set.
private int _sp=0;
public Object[] _data;
/************ Constructors ************/
public Container(){
    _sp=0;
    _data = new Object[INIT_SIZE];
}
public Container(Container other) {  // copy constructor
    this();
    for(int i=0;i<other.size();i++) this.add(other.at(i));
}

/** return true is this collection is empty, else return false. */
public synchronized boolean isEmpty() {return _sp==0;}

/** add an Object to this set */
public synchronized void add (Object p){
    if (_sp==_data.length) rescale(RESCALE);
    _data[_sp] = p;  // shellow copy semantic.
    _sp++;
}   

/** returns the actual amount of Objects contained in this collection */
public synchronized int size() {return _sp;}

/** returns true if this container contains an element which is equals to ob */
public synchronized boolean isMember(Object ob) {
    return get(ob)!=-1;
}

/** return the index of the first object which equals ob, if none returns -1 */
public synchronized int get(Object ob) {
    int ans=-1;
    for(int i=0;i<size();i=i+1)
        if(at(i).equals(ob)) return i;
    return ans;
}

/** returns the element located at the ind place in this container (null if out of range) */
public synchronized Object at(int p){
    if (p>=0 && p<size()) return _data[p];
    else return null;
}

© Stack Overflow or respective owner

Related posts about java

Related posts about multithreading