1 /*
2  * Created on Jun 4, 2008
3  * Created by Paul Gardner
4  *
5  * Copyright (C) Azureus Software, Inc, All Rights Reserved.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18  */
19 
20 
21 package org.gudy.azureus2.core3.util;
22 
23 import org.gudy.azureus2.core3.security.SESecurityManager;
24 
25 public class
26 TimeLimitedTask
27 {
28 	private String		name;
29 	private int			max_millis;
30 	private int			priority;
31 	private task		t;
32 
33 	public
TimeLimitedTask( String _name, int _max_millis, int _priority, task _t )34 	TimeLimitedTask(
35 		String			_name,
36 		int				_max_millis,
37 		int				_priority,
38 		task			_t )
39 	{
40 		name		= _name;
41 		max_millis	= _max_millis;
42 		priority	= _priority;
43 		t			= _t;
44 	}
45 
46 	public Object
run()47 	run()
48 
49 		throws Throwable
50 	{
51 		final Object[]	result	= { null };
52 
53 		final AESemaphore sem = new AESemaphore( name );
54 
55 		final Thread thread =
56 			new Thread( name )
57 			{
58 				public void
59 				run()
60 				{
61 					try{
62 						result[0] = t.run();
63 
64 					}catch( Throwable e ){
65 
66 						result[0] = e;
67 
68 					}finally{
69 
70 						t = null;
71 
72 						sem.releaseForever();
73 					}
74 				}
75 			};
76 
77 		DelayedEvent ev =
78 			new DelayedEvent(
79 				name,
80 				max_millis,
81 				new AERunnable()
82 				{
83 					public void
84 					runSupport()
85 					{
86 						if ( !sem.isReleasedForever()){
87 
88 							SESecurityManager.stopThread( thread );
89 						}
90 					}
91 				});
92 
93 		thread.setPriority( priority );
94 
95 		thread.setDaemon( true );
96 
97 		thread.start();
98 
99 		sem.reserve();
100 
101 		ev.cancel();
102 
103 		if ( result[0] instanceof Throwable ){
104 
105 			throw((Throwable)result[0] );
106 		}
107 
108 		return( result[0] );
109 	}
110 
111 	public interface
112 	task
113 	{
114 		public Object
run()115 		run()
116 
117 			throws Exception;
118 	}
119 }
120