Is it correct to cast an exception within a Synchronized?

Asked

Viewed 65 times

2

In my app there are some threads that access the database and control this competition using the totalcross Lock.

My question is: Can I allow exceptions to be thrown into a Synchronized block ? or have to do something so that the exception is thrown out of its scope ?

Today I keep this from happening.

Follow an example of code used:

    public int executeUpdate(int dbIdx, String sql) {

    int res = 0;

    // secure access for database resource
    synchronized (MainDB.lockDB) {

        try {

            Debug.debug(sql, Debug.DEBUG_LEVEL_DEBUG);

            // Create statement to execute query
            Statement st =  connPool[dbIdx].createStatement();

            // Execute query
            res = st.executeUpdate(sql);

        } catch (SQLException e) {

            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return res;
}
  • Launch or treat/capture?

  • 1

    Whatever. The purpose of the question was to understand how Totalcross behaves when the execution flow is stopped before the end of the Synchronized scope, to understand whether the lock is released or not.

1 answer

2


Releasing exceptions is a normal process in Java development. It has no side effect. The Totalcross virtual machine has exception handling very similar to that of the JVM.

In the international Stack Overflow, they gave a very brief answer on the subject: https://stackoverflow.com/a/2019350/4438007

If the exception is thrown and dealt with within the block synchronized, there is no secret. If the exception is treated beyond the block synchronized, the lock will be returned (and, if any other thread is stopped waiting for the lock, it will therefore continue the lock is released) and the exception will be treated where it is captured.

That one java world article speaks in more detail how JVM handles exceptions. A JVM documentation is also a good read to know about the behavior when making exceptions (I recommend focusing on the sections 2.6 and 2.10).

About synchronization, the same occurs as foreseen in java documentation: at the end of the execution block, the lock is released.

Just to highlight, per hour, Totalcross does not allow using synchronized methods, only synchronized blocks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.