This week's book giveaway is in the Jython/Python forum.
We're giving away four copies of Murach's Python Programming and have Michael Urban and Joel Murach on-line!
See this thread for details.
Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

synchrized  RSS feed

 
Bob Moranski
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I have a question in regard to the following code:
import java.util.*;
import java.math.BigInteger;
public class PrimeList implements Runnable {
private Vector primesFound;
private int numPrimes, numDigits;
public PrimeList(int numPrimes, int numDigits,
boolean runInBackground) {
// Using Vector instead of ArrayList
// to support JDK 1.1 servlet engines
primesFound = new Vector(numPrimes);
this.numPrimes = numPrimes;
this.numDigits = numDigits;
if (runInBackground) {
Thread t = new Thread(this);
// Use low priority so you don't slow down server.
t.setPriority(Thread.MIN_PRIORITY);
t.start();
} else {
run();
}
}
public void run() {
BigInteger start = Primes.random(numDigits);
for(int i=0; i<numPrimes; i++) {>
start = Primes.nextPrime(start);
synchronized(this) {
primesFound.addElement(start);
}
}
}
public synchronized boolean isDone() {
return(primesFound.size() == numPrimes);
}
public synchronized Vector getPrimes() {
if (isDone())
return(primesFound);
else
return((Vector)primesFound.clone());
}
public synchronized int numCalculatedPrimes() {
return(primesFound.size());
}
}
In this code, synchronized methods can not access this object while the code is running within the synchronized block in the for loop?
If that is true, can we achieve the same effect by synchronized(primesFound) in each method instead?
Thank you.
 
Tanveer Rameez
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you synchronize 'this' i.e the whole object, then no synchronized methods can ne accessed by any other thread.But if you synchronize only a variable, then other methods can be accessed by other threads, but those threads will have to wait once the reach any line involving accessing that variable. Here since once a synchronized method is entered, the only variable that is being accessed in the methods in the PrimesFound, synchronizing the variable 'primefound' will have the same effect as synchronizing the 'this' i.e. the object of PrimeList.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!