Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Sychronizing on a static object  RSS feed

 
Ron Goodbin
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all - this is my first post , I am excited.
Anyway down to business - I want to understand
how static obj works in relation to threads.

Here is my class that implements runnable. I am trying to synchronize on
the static int[]. The issue I am having is based on my output it seems
like my threads are not sychronizing on that block.
Any takers - THANKS!


public class MokServlet implements Runnable {
static private int[] theArray={0,1,2};
public MokServlet(){
}
public void run() {
System.out.println(Thread.currentThread().getName()+": enters run()");
System.out.println(Thread.currentThread().getName()+":Static array size="+getSize());

increaseArray();

System.out.println(Thread.currentThread().getName()+":Static array size="+getSize());
System.out.println(Thread.currentThread().getName()+":finished run");

}
public static int[] getArray(){
return theArray;
}
public static int getSize() {return theArray.length;}
public static void increaseArray(){
synchronized (theArray){
System.out.println(Thread.currentThread().getName()+":about to increase size in sychronized");
int[] temp = new int[theArray.length+2];
for (int i=0;i<theArray.length;i++) {
temp[i]=theArray[i];

}
theArray=temp;
try{
Thread.sleep(5000);
}catch(Exception e){}


System.out.println(Thread.currentThread().getName()+":increase finished size="+getSize());
}//end of synchronized block



}

}
 
Stefan Wagner
Ranch Hand
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I changed your code a little, and it seems to work (two Threads, printing 3, 3, 5, 7):

I'm asking two things:
a) How is System.out working - a seperate Thread?
b) In your example, the last access to theArray in the sync-block is via getSize ().
This is a indirect call to theArray.
The last direct call to theArray is before the big sleep happens, so perhaps the sync ends before the sleep?

I don't know the specs that exactly, to tell you whether this is a nice behaviour.
[ May 14, 2004: Message edited by: Stefan Wagner ]
 
Yaroslav Chinskiy
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ron

The dimplest fix for the problem is to sync. increaseArray method.

Also you need to sync. getSize() method. It will prevent T1 from getting the size while T0 is
increasing it.

Once T0 gets lock on sync method, all sync methods in the object are locked)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!