call me from a background thread
760096
private void exportToCsv(File exportFile) {
        FileWriter fileWriter = null;
        exportStatus=true;
        try {
            fileWriter = new FileWriter(exportFile);
            CSVWriter writer = new CSVWriter(fileWriter);
            List<Marker> markers = datastore.getBookmarksAsMarkers(getmMapView());
            String[] headers = new String[] {"Latitude","Longitude","Description","Title"};
            writer.writeNext(headers);
            for (Marker m: markers) {
                String[] items = new String[4];
                items[0] = m.getPosition().getLatitude()+"";
                items[1] = m.getPosition().getLongitude()+"";
                items[2] = m.getSubDescription();
                items[3] = m.getTitle();
                writer.writeNext(items);
            }
        }catch (Exception ex) {
            exportStatus=false;
            ex.printStackTrace();
        } finally {
            if (fileWriter!=null)
                try {
                    fileWriter.close();
                }catch (Exception ex) {}
        }
        final Activity act = getActivity();
        if (act!=null) {
            act.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (exportStatus) {
                        Toast.makeText(act, "Export Complete", Toast.LENGTH_LONG).show();
                    } else
                        Toast.makeText(act, "Export Failed", Toast.LENGTH_LONG).show();
                }
            });
        }
    }
822888
def start_background(wait = 5)
      @server = WEBrick::HTTPServer.new(
        :BindAddress => @options[:host],
        :Port        => @options[:port],
        :AccessLog   => [],
        :Logger      => WEBrick::Log.new(StringIO.new, 7)
      )
      @server.mount('/', Rack::Handler::WEBrick, app)

      @thread = Thread.new { @server.start }
      @thread.abort_on_exception = true
      @thread
    end
39775
@Override
    public Boolean call() throws Exception {
        error.set(null);
        
        List<Callable<Boolean>> subtasks = Lists.newArrayList();
        
        // We are iterating the entire ring using an arbitrary number of threads
        if (this.concurrencyLevel != null || startToken != null|| endToken != null) {
            List<TokenRange> tokens = partitioner.splitTokenRange(
                    startToken == null ? partitioner.getMinToken() : startToken, 
                    endToken == null   ? partitioner.getMinToken() : endToken, 
                    this.concurrencyLevel == null ? 1 : this.concurrencyLevel);
            
            for (TokenRange range : tokens) {
                subtasks.add(makeTokenRangeTask(range.getStartToken(), range.getEndToken()));
            }
        }
        // We are iterating through each token range
        else {
            List<TokenRange> ranges = keyspace.describeRing(dc, rack);
            for (TokenRange range : ranges) {
                if (range.getStartToken().equals(range.getEndToken())) 
                    subtasks.add(makeTokenRangeTask(range.getStartToken(), range.getEndToken()));
                else
                    subtasks.add(makeTokenRangeTask(partitioner.getTokenMinusOne(range.getStartToken()), range.getEndToken()));
            }
        }
        
        try {
            // Use a local executor
            if (executor == null) {
                ExecutorService localExecutor = Executors
                        .newFixedThreadPool(subtasks.size(),
                            new ThreadFactoryBuilder().setDaemon(true)
                                .setNameFormat("AstyanaxAllRowsReader-%d")
                                .build());
                
                try {
                    futures.addAll(startTasks(localExecutor, subtasks));
                    return waitForTasksToFinish();
                }
                finally {
                    localExecutor.shutdownNow();
                }
            }
            // Use an externally provided executor
            else {
                futures.addAll(startTasks(executor, subtasks));
                return waitForTasksToFinish();
            }
        }
        catch (Exception e) {
            error.compareAndSet(null, e);
            LOG.warn("AllRowsReader terminated. " + e.getMessage(), e);
            cancel();
            
            throw error.get();
        }
    }
315665
def _call(self, method, url, params):
        """"""
        request_params = {}
        if method == 'GET':
            request_params['params'] = params
        elif method == 'POST':
            request_params['data'] = params
        response = requests.request(method, url, **request_params)
        return response
1172698
def startThread(self):
        """"""
        if self._thread is not None:
            return
        self._thread = NSThread.alloc().initWithTarget_selector_object_(self, 'runPowerNotificationsThread', None)
        self._thread.start()
94818
def _thread_worker(self):
        """"""
        while self._running:
            # Retrieve next cmd, or block
            packet = self._queue.get(True)
            if isinstance(packet, dict) and QS_CMD in packet:
                try:
                    self._callback_listen(packet)
                except Exception as err:  # pylint: disable=broad-except
                    _LOGGER.error("Exception in callback\nType: %s: %s",
                                  type(err), err)
            self._queue.task_done()
546356
def batch_call(self, calls):
        """"""
        req = self.protocol.create_batch_request()

        for call_args in calls:
            req.append(self.protocol.create_request(*call_args))

        return self._send_and_handle_reply(req)
834131
def run(self):
        """"""
        if win_based:
            raise NotImplementedError("Please run main_loop, "
                                      "backgrounding not supported on Windows")
        self.background_process = mp.Process(target=self.main_loop)
        self.background_process.start()
436632
def call(self, method, params, callback=None):
        """"""
        self._wait_for_connect()
        self.ddp_client.call(method, params, callback=callback)
867545
def callToThread(method):
    
    def func_wrapped(self, *args, **kwargs):
      self.thread.execute_queue.put_nowait((threading.get_ident(), method, args, kwargs))
      return self.waitResult()
    return func_wrapped
557703
def run_on_ui_thread(f):
    '''
    '''
    def f2(*args, **kwargs):
        Runnable(f)(*args, **kwargs)
    return f2
62764
public <V> V call(Callable<V> callable) throws Exception {
		initStartTotal();
		long startInvokation = System.currentTimeMillis();
		V result = callable.call();
		invoked(System.currentTimeMillis() - startInvokation);
		return result;
	}
511938
def _make_call(self, call):
        """"""
        try:
            request = urllib2.Request(self.config.environment, E.tostring(call))
            request.add_header('Content-Type', 'text/xml')
            response = urllib2.urlopen(request).read()
            response = E.fromstring(response)
            response_json = parse_response(response)
        except urllib2.HTTPError:
            raise AuthorizeConnectionError('Error processing XML request.')

        # Exception handling for transaction response errors.
        try:
            error = response_json.transaction_response.errors[0]
            raise AuthorizeResponseError(error.error_code, error.error_text, response_json)
        except (KeyError, AttributeError):  # Attempt to access transaction response errors
            pass

        # Throw an exception for invalid calls. This makes error handling easier.
        if response_json.messages[0].result_code != 'Ok':
            error = response_json.messages[0].message
            raise AuthorizeResponseError(error.code, error.text, response_json)

        return response_json
202719
def call_async(self, fn, *args, **kwargs):
        
        return self.default_call_chain.call_async(fn, *args, **kwargs)
198730
def __postCallAction(self, event):
        
        aThread = event.get_thread()
        retval  = self._get_return_value(aThread)
        self.__callHandler(self.__postCB, event, retval)
1113281
def _loop_thread_main(self):
        """"""

        asyncio.set_event_loop(self.loop)
        self._loop_check.inside_loop = True

        try:
            self._logger.debug("Starting loop in background thread")
            self.loop.run_forever()
            self._logger.debug("Finished loop in background thread")
        except:  # pylint:disable=bare-except;This is a background worker thread.
            self._logger.exception("Exception raised from event loop thread")
        finally:
            self.loop.close()
1175506
def call(self, method, params, callback=None):
        """"""
        cur_id = self._next_id()
        if callback:
            self._callbacks[cur_id] = callback
        self.send({'msg': 'method', 'id': cur_id, 'method': method, 'params': params})