SingleSWTRequest utility class now actually does what it is supposed to
[Mograsim.git] / plugins / net.mograsim.plugin.core / src / net / mograsim / plugin / util / SingleSWTRequest.java
1 package net.mograsim.plugin.util;
2
3 import java.util.concurrent.atomic.AtomicBoolean;
4
5 import org.eclipse.swt.widgets.Display;
6
7 /**
8  * A utility class that requests the asynchronous execution of a Runnable in the SWT Thread. Making a new request before the old one is
9  * processed will override the old request.
10  */
11 public class SingleSWTRequest
12 {
13         private AtomicBoolean waiting = new AtomicBoolean();
14         private Runnable request;
15
16         public void request(Runnable request)
17         {
18                 synchronized (waiting)
19                 {
20                         this.request = request;
21                         if (!waiting.get())
22                         {
23                                 waiting.set(true);
24                                 Display.getDefault().asyncExec(() ->
25                                 {
26                                         synchronized (waiting)
27                                         {
28                                                 waiting.set(false);
29                                                 this.request.run();
30                                         }
31                                 });
32                         }
33                 }
34         }
35 }