Solved

Why Synchronize in this program??

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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…

744 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

11 Experts available now in Live!

Get 1:1 Help Now