Solved

Why Synchronize in this program??

Posted on 2003-11-23
8
506 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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

691 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