Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive-3.4/sources/HeuristicLab.Clients.Hive/3.4/ConcurrentJobDownloader.cs @ 6373

Last change on this file since 6373 was 6373, checked in by cneumuel, 13 years ago

#1233

  • moved ExperimentManager into separate plugin
  • moved Administration into separate plugin
File size: 4.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Threading;
24using System.Threading.Tasks;
25using HeuristicLab.Common;
26using HeuristicLab.Hive;
27
28namespace HeuristicLab.Clients.Hive {
29  /// <summary>
30  /// Downloads and deserializes jobs. It avoids too many jobs beeing downloaded or deserialized at the same time to avoid memory problems
31  /// </summary>
32  public class ConcurrentJobDownloader<T> where T : class, IJob {
33    private bool abort = false;
34    // use semaphore to ensure only few concurrenct connections and few SerializedJob objects in memory
35    private Semaphore downloadSemaphore;
36    private Semaphore deserializeSemaphore;
37   
38    public ConcurrentJobDownloader(int concurrentDownloads, int concurrentDeserializations) {
39      downloadSemaphore = new Semaphore(concurrentDownloads, concurrentDownloads);
40      deserializeSemaphore = new Semaphore(concurrentDeserializations, concurrentDeserializations);
41      TaskScheduler.UnobservedTaskException += new EventHandler<UnobservedTaskExceptionEventArgs>(TaskScheduler_UnobservedTaskException);
42    }
43
44    public void DownloadJob(Job job, Action<Job, T> onFinishedAction) {
45      Task<T> task = Task<JobData>.Factory.StartNew((x) => DownloadJob(x), job.Id)
46                                     .ContinueWith((x) => DeserializeJob(x.Result));
47      task.ContinueWith((x) => OnJobFinished(job, x, onFinishedAction), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion);
48      task.ContinueWith((x) => OnJobFailed(job, x, onFinishedAction), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnFaulted);
49    }
50
51    private void OnJobFinished(Job job, Task<T> task, Action<Job, T> onFinishedAction) {
52      onFinishedAction(job, task.Result);
53    }
54    private void OnJobFailed(Job job, Task<T> task, Action<Job, T> onFinishedAction) {
55      task.Exception.Flatten().Handle((e) => { return true; });
56      OnExceptionOccured(task.Exception.Flatten());
57      onFinishedAction(job, null);
58    }
59
60    protected JobData DownloadJob(object jobId) {
61      downloadSemaphore.WaitOne();
62      deserializeSemaphore.WaitOne();
63      JobData result;
64      try {
65        if (abort) return null;
66        result = ServiceLocator.Instance.CallHiveService(s => s.GetJobData((Guid)jobId));
67      }
68      finally {
69        downloadSemaphore.Release();
70      }
71      return result;
72    }
73
74    protected T DeserializeJob(JobData jobData) {
75      try {
76        if (abort || jobData == null) return null;
77        Job job = ServiceLocator.Instance.CallHiveService(s => s.GetJob(jobData.JobId));
78        if (job == null) return null;
79        var deserializedJob = PersistenceUtil.Deserialize<T>(jobData.Data);
80        jobData.Data = null; // reduce memory consumption.
81        return deserializedJob;
82      }
83      finally {
84        deserializeSemaphore.Release();
85      }
86    }
87
88    private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) {
89      e.SetObserved(); // avoid crash of process because task crashes. first exception found is handled in Results property
90      OnExceptionOccured(new HiveException("Unobserved Exception in ConcurrentJobDownloader", e.Exception));
91    }
92
93    public event EventHandler<EventArgs<Exception>> ExceptionOccured;
94    private void OnExceptionOccured(Exception exception) {
95      var handler = ExceptionOccured;
96      if (handler != null) handler(this, new EventArgs<Exception>(exception));
97    }
98  }
99}
Note: See TracBrowser for help on using the repository browser.