Solved

Why Synchronize in this program??

Posted on 2003-11-23
8
502 Views
Last Modified: 2010-03-31
what is the importance of synchronize key word in this program,what will happen if we remove that from each method(that use it,specially getParticles(),setParticles())??

Particle {
 protected int x;
 protected int y;
 protected final Random rng = new Random();
 
 public Particle(int initialX, int initialY) {
  x = initialX;
  y = initialY;
 }    

 public synchronized void move() {
  x += rng.nextInt(10) - 5;
  y += rng.nextInt(20) - 10;
 }

 public void draw(Graphics g) {
  int lx, ly;
  synchronized (this) { lx = x; ly = y; }
  g.drawRect(lx, ly, 10, 10);
 }
}
class ParticleCanvas extends Canvas {

 private Particle[ ] particles = new Particle[0];

 ParticleCanvas(int size) {
  setSize(new Dimension(size, size));
 }
 
 // intended to be called by applet
 protected synchronized void setParticles(Particle[ ] ps) {
  if (ps == null)
   throw new IllegalArgumentException("Cannot set null");

  particles = ps;
 }

 protected synchronized Particle[ ] getParticles() {
  return particles;
 }
 
 public void paint(Graphics g) { // override Canvas.paint
  Particle[ ] ps = getParticles();

  for (int i = 0; i < ps.length; ++i)
   ps[i].draw(g);

 }
}
public class ParticleApplet extends Applet {

 protected Thread[ ] threads = null; // null when not running

 protected final ParticleCanvas canvas
                   = new ParticleCanvas(100);

 public void init() { add(canvas); }

 protected Thread makeThread(final Particle p) { // utility
  Runnable runloop = new Runnable() {
   public void run() {
    try {
     for(;;) {
      p.move();
      canvas.repaint();
      Thread.sleep(100); // 100msec is arbitrary
     }
    }
    catch (InterruptedException e) { return; }
   }
  };
  return new Thread(runloop);
 }

 public synchronized void start() {
  int n = 10; // just for demo

  if (threads == null) { // bypass if already started
   Particle[ ] particles = new Particle[n];
   for (int i = 0; i < n; ++i)
    particles[i] = new Particle(50, 50);
   canvas.setParticles(particles);

   threads = new Thread[n];
   for (int i = 0; i < n; ++i) {
    threads[i] = makeThread(particles[i]);
    threads[i].start();
   }
  }
 }

 public synchronized void stop() {
  if (threads != null) { // bypass if already stopped
   for (int i = 0; i < threads.length; ++i)
    threads[i].interrupt();
   threads = null;
  }
 }
}
0
Comment
Question by:asela_it1
  • 2
  • 2
8 Comments
 

Accepted Solution

by:
popaking earned 43 total points
ID: 9808123
Pretty simple BUT important,

Basically you want those methods with synchronized keywords to happen like transactions (exclusively), they cannot be interrupted in the middle. Either all of it happens or NONE of it happens.

In the above program, i dont see if removing 'synchronized' from getParticles and setParticles would effect anything.

0
 
LVL 15

Assisted Solution

by:JakobA
JakobA earned 41 total points
ID: 9808194
syncronizing the methods  getParticles() and setParticles()  in class canvas has no effect at all. well it might slow down the program slightly.

none of the code in either of the 2 methods need to be seen as 'a transaction that must be completed before someone else may start doing it again'.
0
 
LVL 15

Expert Comment

by:JakobA
ID: 9808217
0
 

Expert Comment

by:popaking
ID: 9808368
This is entirely true, there is no need for it in this code given above..
But i am generaly explaining as what synchronized would achieve.
0
 

Assisted Solution

by:werdy
werdy earned 41 total points
ID: 9819249
The synchronized keyword on the getParticles and setParticles in this case do nothing, since there is no potential for them to be called  simultaneously by multiple threads. If they where however, I would encourage retaining the synchronization  to elimnate possibly discrepencies between main memory and working (thread) memory, though I have not analyzed it sufficiently to prove that it would be necessary. Such descrepancies would be dependant on the implementaiton of the JVM in use, and may vary from one JVM to another.

The synchronization on move() and draw() of Particle however, should be retained. If my understanding is correct, draw() will not occur in the same Thread as move(). If they are not synchronized but are called from seperate threads, there is the potential for a draw to occur after the x value is updated in move() but before the y value is updated, producing the rectangle at the wrong location.

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Where to store the queries for modification of table 4 55
java.io.BufferedReader   readLine()  //returns the entire file ? 4 60
table example 4 24
arguments to jar 5 15
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This video teaches viewers about errors in exception handling.

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now