Is it correct to throw an exception within a synchronized?

2

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

My question is: Can I allow exceptions to be thrown within a synchronized block? or do I have to do something to get the exception thrown out of its scope?

Today I prevent this from happening.

Here is an example 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;
}
    
asked by anonymous 25.05.2017 / 15:13

1 answer

2

Triggering exceptions is a normal process in Java development. It has no side effects whatsoever. The TotalCross virtual machine has exception handling very similar to that of the JVM.

At Stack Overflow International, they gave a very succinct answer on the subject: link

If the exception is thrown and handled within the block synchronized , there is no secret. If the exception is handled in addition to the synchronized block, lock will be returned (and if any other thread is stopped waiting lock , it will continue because lock is released) and the exception will be handled where it is captured.

This Java World article the> talks in more detail how the JVM handles the exceptions. The JVM documentation is also a good read to learn about the behavior when throwing exceptions (I recommend focusing on the 2.6 sections. and 2.10 ).

On synchronization, the same thing you see in Java : When you reach the end of the execution block, lock is released.

Just to note, for the time being, TotalCross does not allow you to use synchronized methods, just synchronized blocks.

    
25.05.2017 / 15:49