java - Using synchronized block to protect against infinite loops -


i'm developing app in test cases, goes on infinite loop, if redo same tests, goes on well. prevent it, i'm using secondary thread monitor time passed since start of task, i'm not using synchronized blocks, because don't know how to.

here example:

public class threadharvest {     private static final reentrantlock lock = new reentrantlock();     private static boolean safe;      public static void main(string[] args) throws interruptedexception     {         thread task = new thread(() ->{             lock.lock();             safe = false;              (long = 10000000l; > 0l; --i)                 system.out.println(i);              safe = true;             lock.unlock();              system.out.println("safe ended!");         });          task.start();          while (lock.islocked() == false);          lock.trylock(5, timeunit.seconds);          if (!safe)         {             task.stop();             system.out.println("force ended!");         }     } } 

also, there specific area guaranteed safe, after lock released. , know stop method deprecated, if happen have ideas make less error prone, i'd thankful :d

i don't understand question here general comments code.

  • you should never have spin loop that. i'd add thread.sleep(10); or something.
  • with locks, should put unlock in lock; try { } { unlock; }. know lock unlocked if throws exception.
  • if accessing field in 2 different threads must protect somehow. use atomicboolean safe or mark volatile boolean otherwise main thread might not see changes it. there no guarantees of memory synchronization islocked() or trylock().
  • instead of lock , safe, how trying task.join(5, timeunit.seconds) , test if (task.isalive()) { killitwithfire(); }.

i'm developing app in test cases, goes on infinite loop,

seems me should be concentrating time fixing problem. thread.stop() real hack.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -