Solved

Why Synchronize in this program??

Posted on 2003-11-23
8
504 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
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 tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

726 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