by

Safe Realization of a Thread in Java

Manage threads in Java can be tricky, most of all the stop of them. With this class no littering thread will be left behind.
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/38562/Safe-Realization-of-a-Thread-in-Java?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
import java.lang.Thread; import java.util.List; public class MySafeThread implements Runnable { private static MySafeThread singleton = null; /** * Synchronization variable for the safe instantiation of the singleton */ private static Object synchSingleton = new Object(); /** * The actual thread object */ private Thread thread; /** * The flag signalling whether the thread is running or not */ private boolean threadRunning = false; private MySafeThread(){ } public void restart() { closeThread(); startThread(); } /** * Closes the thread, releasing all the resources */ public void closeThread(){ threadRunning = false; //break the execution of the thread and wait until the last loop is finished: Thread moribond = this.thread; this.thread=null; moribond.interrupt(); singleton = null; } /** * Retrieves the singleton instance of the class; if * the singleton has not yet been instantiated, it builds * a new instance using the protected constructor. * @return The singleton instance of the class */ public static MySafeThread get(){ if (singleton == null) { synchronized (synchSingleton) { if (singleton == null) { singleton = new MySafeThread(); } } } return singleton; } /** * The main method of the thread which listens for new responses available, and * sends them via IPC */ public void run(){ Thread t = Thread.currentThread(); threadRunning = true; while(threadRunning) { //do something... } } /** * Starts the thread */ public void startThread(){ //only a single instance of the thread can run: if (threadRunning) return; this.thread = new Thread(this, "GiveANameToTheThread"); this.thread.start(); } }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus