Java – Android Studio – Unable to catch exception lock surface

Android Studio – Unable to catch exception lock surface… here is a solution to the problem.

Android Studio – Unable to catch exception lock surface

Hello, I made a game in Android Studio. Sometimes when I close and restart the app on the emulator, I get the following spam in logcat:

Exception locking surface
java.lang.IllegalStateException: Surface was already locked

I tried surrounding canvas with try-catch block = this.surfaceHolder.lockCanvas(); But no exception is caught. Is there a way to check if a Canvas is locked before attempting to lock it?

This is my code in the class

    while (running) {
        startTime = System.nanoTime();
        canvas = null;

try {
     canvas = this.surfaceHolder.lockCanvas();
            synchronized (surfaceHolder) {
                 update game state
                 draws the canvas on the panel

} catch(Exception e){e.printStackTrace(); }finally {
             in case of an exception the surface is not left in
             an inconsistent state
            if (canvas != null) {
                try {


                catch(Exception e){e.printStackTrace(); }


You can identify and check with the boolean constant;

    //create the boolean;
private boolean cLocked = false;

 if (!cLocked){
    canvas = this.surfaceHolder.lockCanvas();
    cLocked = true;

if (cLocked) {
    cLocked = false;

This will prevent exceptions. It does not lock when it is already locked, and vice versa.

Related Problems and Solutions