tags:

views:

70

answers:

2

What does this line from the following code sample mean? "synchronized (_surfaceHolder) {_panel.onDraw(c);}"

I can guess what it does, but what is it called and how does it works? Is it a nameless synchronized function?

class TutorialThread extends Thread {
    private SurfaceHolder _surfaceHolder;
    private Panel _panel;
    private boolean _run = false;

    public TutorialThread(SurfaceHolder surfaceHolder, Panel panel) {
        _surfaceHolder = surfaceHolder;
        _panel = panel;
    }

    public void setRunning(boolean run) {
        _run = run;
    }

    @Override
    public void run() {
        Canvas c;
        while (_run) {
            c = null;
            try {
                c = _surfaceHolder.lockCanvas(null);
                synchronized (_surfaceHolder) {
                    _panel.onDraw(c);
                }
            } finally {
                // do this in a finally so that if an exception is thrown
                // during the above, we don't leave the Surface in an
                // inconsistent state
                if (c != null) {
                    _surfaceHolder.unlockCanvasAndPost(c);
                }
            }
        }
    }
A: 

I think you're mistaking use of the synchronized keyword for this "nameless" function. The code

synchronized (_surfaceHolder) {
    _panel.onDraw(c);
}

is simply locking on _surfaceHolder before it executes the line _panel.onDraw(c), and then releases that lock once it's done.

Matt Ball
Thanks, now it make more.
Justin O
+2  A: 

There is no hidden method there, the code is just synchronizing on the _surfaceHolder object. Basically, it says to get a lock on _surfaceHolder before executing the lines in {}'s.

See Intrinsic Locks and Synchronization.

Mayra
Thanks! I didn't know what it was called, so couldn't google it out :p
Justin O