View Javadoc

1   package cz.cuni.amis.pogamut.defcon.utils;
2   
3   import java.lang.reflect.Method;
4   import java.util.concurrent.CountDownLatch;
5   import java.util.concurrent.TimeUnit;
6   
7   import javabot.PogamutJBotSupport;
8   
9   /**
10   * Container for execution of queries from game info in the main thread from
11   * other threads.
12   * 
13   * @author Radek 'Black_Hand' Pibil
14   * 
15   */
16  public class SyncMethodExecContainer {
17  	public volatile Method method;
18  	public volatile Object[] parameters;
19  	public volatile Object returnValue = null;
20  	public volatile Object lock = new Object();
21  	public volatile boolean used = false;
22  
23  	public SyncMethodExecContainer(Method method, Object[] parameters) {
24  
25  		if (method == null)
26  			throw new IllegalArgumentException(
27  					"method argument cannot be null.");
28  
29  		this.method = method;
30  		this.parameters = parameters;
31  	}
32  
33  	/**
34  	 * Called in the main thread to execute herein contained method with a given
35  	 * parameters and collecting the return value.
36  	 */
37  	public void execute() {
38  		synchronized (lock) {
39  			try {
40  				this.returnValue = method.invoke(null, parameters);
41  			} catch (Exception e) {
42  				e.printStackTrace();
43  			} finally {
44  				latch.countDown();
45  			}
46  		}
47  	}
48  	
49  	private final CountDownLatch latch = new CountDownLatch(1);
50  
51  	/**
52  	 * Enqueue and wait for execution of the herein contained method in the main
53  	 * thread.
54  	 * 
55  	 * @return
56  	 */
57  	public Object syncCallInMainThread() {
58  
59  		synchronized (lock) {
60  			if (used)
61  			throw new RuntimeException(
62  					"Called twice! Previous call must finish first!");
63  			used = true;
64  		}
65  
66  
67  		PogamutJBotSupport.addQuery(this);
68  		try {
69  			latch.await(10000, TimeUnit.MILLISECONDS);
70  		} catch (InterruptedException e) {
71  			PogamutJBotSupport.writeToConsole("Intteruped waiting");
72  		} catch (Exception e) {
73  			PogamutJBotSupport.writeToConsole("Exception!");
74  			e.printStackTrace();
75  			e.getCause().printStackTrace();
76  		}
77  
78  		return returnValue;
79  	}
80  	
81  	public Object getLock() {
82  		return lock;
83  	}
84  }