adding synchronization on "val" due to possible race conditions (thanks to Damien Octeau for reporting this!)