Exceptions in Executor.submit

Run the following test code:
public class Test {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();
        executor.submit(new Runnable() {
            public void run() {
                throw new RuntimeException("This is a runtime exception");
}Why doesn't the stack trace show up on System.out as it would normally do if I had executed the runnable in a new Thread? Is there anyway short of wrapping the whole run method in a try-catch block of getting that stack trace.
TIA.

When you submit your Runnable to the ExecutorService you get a Future back. Calling get() on that Future will result in an ExecutionException being thrown. The cause of that exception is your RuntimeException:
import java.util.concurrent.*;
public class Test {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();
        Future<?> f = executor.submit(new Runnable() {
            public void run() {
                throw new RuntimeException("This is a runtime exception");
        try {
            f.get();
        catch (Exception e) {
            e.printStackTrace();
}I've recently started to play around with these things myself, and here is my understanding of it:
An ExecutorService uses a FutureTask by default when you submit a Runnable (see the source code for AbstractExecutorService). That FutureTask basically wraps your Runnable inside atry { ... } catch (Throwable) {... }which explains why your exception doesn't slip through. Instead, the throwable is stored inside the FutureTask. When you call get() on the Future, the throwable is wrapped inside an ExecutionException, as described above.

Similar Messages

  • Exceptions handling  for  "submit of  Insert Report "

    Dear Experts,
    i need to handle Exception "syntax Error" when Submit the inserted report.
    i tried " try and Catch " but failed to catch Dump Error.
    for example:
    Data  CODE TYPE  TABLE OF String .
    APPEND   'REPORT ZDYN.'                                 TO Code .
    APPEND 'Data Var1 type I   .'          TO Code .
    append 'if var > 10 '                         to Code .
    append 'Write ''Success''  .  '            to Code .
    append 'else. '                                  to Code .
    append 'Write ''Failed'' . '                   to Code .
    append 'EndIf . '                               to Code .
    TRY .
        data Prog TYPE c LENGTH 50 VALUE  'ZDYN'.
        INSERT REPORT Prog FROM CODE .
        SUBMIT Prog AND RETURN .
      CATCH CX_ROOT  .
        raise SYNTAX_ERROR .
    ENDTRY.
    " in the inserted Report the Variable Name is Var1 NOT Var So it will be Syntax error " DUMP Error ".
    Thanks in advance

    Hi,
    First write the code in a program and check what error you get and try to handle that particular error.
    Also a full stop is missing in the code ...
    REPORT ZDYN.
    Data Var1 type I.
    if var > 10 .
    Data CODE TYPE TABLE OF String .
    APPEND 'REPORT ZDYN.' TO Code .
    APPEND 'Data Var1 type I .' TO Code .
    append 'if var > 10 .' to Code . <--  Put a full stop here ..
    append 'Write ''Success'' . ' to Code .
    append 'else. ' to Code .
    append 'Write ''Failed'' . ' to Code .
    append 'EndIf . ' to Code .
    Regards,
    Srini.

  • Unhandled win32 exception occured using "Submit by Email" btn

    A form created using Adobe Designer 7.0 has a "Submit by Email" button on it. When users click this button, instead of attaching a data file to their email so they can email the info to our staff, it instead immediately generates an error: "An unhandled win32 exception occurred in AcroRd32.exe [####] (various numbers)... I don't have Just-In-Time debugging installed, and wouldn't know how to fix this anyway...
    Any ideas why this error is occurring and how to fix it? We don't have funds to upgrade to newer software at this time.
    Thanks!!
    --DB

    reinstall your twain device drivers. scanners, cameras, multi-funciton printers, etc.

  • CNTL_ERROR exception when using 'submit report '

    Hi,
      I am trying to use Submit statement as follows..
    submit PPCMP000  with s_werks  EQ 'SAS1'
                                  with s_aufnr in range_tab
                                  exporting list to memory
                                  and return.
    When i use the submit statement without 'list to memory' it is working fine. But whn i add tht, it showing the following dump.
    <b>" A RAISE statement in the program "CL_GUI_CONTROL================CP" raised the
      exception
    condition "CNTL_ERROR".
    METHOD SET_VISIBLE .
    (visible)
      data: temp_visible(1).
      temp_visible = cl_gui_control=>visible_true.
      case visible.
        when '1'.
        when 'X'.
        when 'x'.
        when 'TRUE'.
        when others.
          temp_visible = cl_gui_control=>visible_false.
      endcase.
    check handle
      IF ME->H_CONTROL IS INITIAL.
        RAISE CNTL_ERROR.
      ENDIF.
    </b>
    Is there any settings needs to be done?
    Can any one help me in this??
    Thanx,
    Sivagami.R

    Hi,
    It's a standard program.
    I have created a transaction, and I'm now using call transaction to bypass the error. (But I would prefer to use submit instruction.)
    Thanks for your help.
    Best regards,
    Bruno

  • Submit by e-mail difficulty, because of trial?

    I recently downloaded the trial version of LiveCycle to see if it would be a good fit for my company. It seems to be except for the submit by e-mail button will only allow me to submit in .xml, I've read up on how to fix this and even tried using the mailto command with a regular button (it doesn't even realize I'm trying to send an e-mail when I do that). Is this simply because I'm using the trial version and an issue that I won't have once I purchase the full version? Thanks for any help you can give.

    try the following JS code in "click" event of a regular button which will compose the email and attach a copy of completed form in PDF format.
    var subj = "Service Agreement Request";
    var ebody = "You may attach additional attachments if you have. But do not edit the Subject line."
    event.target.submitForm({cURL:"[email protected]?subject="+subj+"&body="+ebody,cSubmitAs:"PDF",cCharset:"utf-8"});

  • MY own Executors class

    The point of this would be something like Executors.newFixedThreadPool().
    Comment/suggest/criticize on it please? I just wanted to take a whack at it :p
    import java.util.Queue;
    import java.util.concurrent.LinkedBlockingQueue;
    public class ExecutionService {
         public static void main(String[] args) throws Exception {
              ExecutionService executor = new ExecutionService();
              Runnable test1 = new Runnable() {
                   @Override
                   public void run() {
                        System.out.println("Test one complete!");
              Runnable test2 = new Runnable() {
                   @Override
                   public void run() {
                        System.out.println("Test two complete!");
              executor.executeAndWait(test1);
              executor.executeImmediately(test2);
         public ExecutionService() {
              runnableTasks = new LinkedBlockingQueue<Runnable>(Integer.MAX_VALUE);
              final int NUM_PROCESSORS = Runtime.getRuntime().availableProcessors();
              for(int i = 0; i < NUM_PROCESSORS; i++) {
                   createNewExecutor();
         public Executor createNewExecutor() {
              return new Executor(new Runnable() {
                   @Override
                   public void run() {
                        try {
                             for(;;) {
                                  getNewTask().run();     
                        } catch(InterruptedException e) {
                             e.printStackTrace();
                        } finally {
                             createNewExecutor();
         public boolean executeImmediately(Runnable task) {
              return runnableTasks.offer(task);
         public void executeAndWait(Runnable task) throws InterruptedException {
              runnableTasks.put(task);
         public Runnable getNewTask() throws InterruptedException {
              synchronized(this) {
                   return runnableTasks.take();
         private LinkedBlockingQueue<Runnable> runnableTasks;
    public class Executor {
         public Executor(Runnable task) {
              Thread t = new Thread(task);
              t.setDaemon(true);
              t.start();
    }Edited by: Jadz_Core on Aug 6, 2009 4:37 PM

    Hopefully it is to satisfactory now :)
    import java.util.Queue;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.concurrent.BlockingQueue;
    public class ExecutionService {
         public static void main(String[] args) throws Exception {
              ExecutionService executor = new ExecutionService();
              Runnable test1 = new Runnable() {
                   @Override
                   public void run() {
                        System.out.println("Test one complete!");
              Runnable test2 = new Runnable() {
                   @Override
                   public void run() {
                        System.out.println("Test two complete!");
              executor.waitToExecute(test1);
              executor.executeImmediately(test2);
         public ExecutionService() {
              runnableTasks = new LinkedBlockingQueue<Runnable>(Integer.MAX_VALUE);
              initializeExecutors();
         public ExecutionService(BlockingQueue<Runnable> blockingQueue) {
              runnableTasks = blockingQueue;
              initializeExecutors();
         private final void initializeExecutors() {
              final int NUM_PROCESSORS = Runtime.getRuntime().availableProcessors();
              for(int i = 0; i < NUM_PROCESSORS; i++) {
                   createNewExecutor();
                   ++numThreadsRunning;
         private final Runnable getPermTask() {
              return new Runnable() {
                   @Override
                   public void run() {
                        Exception ex = null;
                        try {
                             while(continueRunning) {
                                  getNewTask().run();     
                        } catch(InterruptedException e) {
                             (ex = e).printStackTrace();
                        } catch(Exception e) {
                             (ex = e).printStackTrace();
                        } finally {
                             if(ex != null) {
                                  createNewExecutor();
         private Executor createNewExecutor() {
              return new Executor(getPermTask());
         private Runnable getNewTask() throws InterruptedException {
              return runnableTasks.take();
         public boolean executeImmediately(Runnable task) throws Exception {
              if(!continueRunning) {
                   throw new Exception("ExecutorService instance is shut down");
              return runnableTasks.offer(task);
         public void waitToExecute(Runnable task) throws InterruptedException, Exception {
              if(!continueRunning) {
                   throw new Exception("ExecutorService instance is shut down");
              runnableTasks.put(task);
         public void shutDown() {
              continueRunning = false;
              Runnable emptyTask = new Runnable() {
                   @Override
                   public void run() {
                        return;
              for(int i = 0; i < numThreadsRunning; i++) try {
                   waitToExecute(emptyTask);
              } catch(InterruptedException e) {
                   System.out.println("Could not shut down!");
                   e.printStackTrace();
              } catch(Exception e) {
                   e.printStackTrace();
         private int numThreadsRunning = 0;
         private volatile boolean continueRunning = true;
         private BlockingQueue<Runnable> runnableTasks;
    class Executor {
         public Executor(Runnable task) {
              Thread t = new Thread(task);
              t.setDaemon(true);
              t.start();
    }

  • Using threads and collecting responses

    Hello,
    I am doing multiple requests to diferent web services from diferent providers. I want to do the requests simultaneously and I think the best way is using threads. I am thinking to create a main class that creates a thread instance for every request (max 5) and then wait for the responses with a timeout. What is best way to implement this? Is there any standard or typical strategy? Different points to consider are:
    - time out, the main class can't wait for ever the threads to end.
    - how every thread passes the response from de web service to the main class.
    Thanks in advance.

    Hi,
    best way to do this may be using an executor service. I cant describe this in detail here..basicly you have to create a executor
    ExecutorService executor = Executors.newCachedThreadPool();then you create so called "Callables" which are like Runnables, but return a result. There you implement your thread functionality in the "call" method.
    public class testCallable implements Callable{
              public Object call() throws Exception {
    }in your controlling class you add these to your executor service and assign the results to a Future (which is a nonblocking operation).
        // make a new Thread for each resouce
              Future[] futures = new Future[5];
              for (int i = 0; i < 5; i++) {
                   futures[i] = executor.submit(new testCallable());
              }then you retrive the result. You can assign a timeout there.
    try {
                 long timeoutTime = System.currentTimeMillis() + timeout;
              for (int i = 0; i < futures.length; i++) {
                   long remainingTime = Math.max(0, timeoutTime
                             - System.currentTimeMillis());
                   try {
                        Result result = (Result) futures.get(
                                  remainingTime, TimeUnit.MILLISECONDS);
    look at
    http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html
    for details
    Greetings
    Brash

  • Why ScheduledThreadPoolExecutor is not respecting the delay?

    I have a Customized implementation for ScheduledThreadPoolExecutor using which I am trying to execute a task for continuous execution. The problem I have faced here with the implementation is, some tasks executed continuously where as two of them are not respecting the delay and executed continuously. I am using the scheduleWithFixedDelay method.
    Even I have tried reproducing, but I couldn't.
    Here is my customized implementation.
    package com.portware.utils.snapmarketdata.test;
    import java.util.Collections;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Set;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.RejectedExecutionHandler;
    import java.util.concurrent.ScheduledFuture;
    import java.util.concurrent.ScheduledThreadPoolExecutor;
    import java.util.concurrent.ThreadFactory;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.atomic.AtomicInteger;
    import com.indigo.utils.Log;
    * To schedule the tasks in timely manner.
    public class TestScheduledExecutorService  {
      private static String CLASS_NAME = TestScheduledExecutorService.class.getName();
      protected final ThreadPoolExecutor executor;
      static int totalCount = 0;
      public static void main(String[] args) throws InterruptedException {
        TestScheduledExecutorService executorService = new TestScheduledExecutorService("Test", 10, null);
        final AtomicInteger integer = new AtomicInteger();
        final Set<Integer> testSet = new HashSet<Integer>();
        for (int i = 0; i < 10; i++) {
          testSet.add(i);
        Iterator<Integer> iterator = testSet.iterator();
        synchronized (testSet) {
        while(iterator.hasNext()) {
          integer.set(iterator.next());
          executorService.submitTaskForContinuousExecution(new Runnable() {
          @Override
          public void run() {
              System.out.println(Thread.currentThread().getName()+" Hello : "+integer.get() + " count value is:"+totalCount++);
        }, integer.toString());
        while (true) {
          synchronized (TestScheduledExecutorService.class) {
            TestScheduledExecutorService.class.wait();
      private static class MyRunnableTask implements Runnable{
        ScheduledFuture<?> future;
         * The task to be run.
        private Runnable runnable;
         * The number of attempt.
        private int count;
         * Maximum attempts configured under TCA configuration.
        private int maximumAttempts;
        private String id;
        public MyRunnableTask(Runnable runnable, int maximumAttempts, String id) {
          this.runnable = runnable;
          this.maximumAttempts = maximumAttempts;
          this.id = id;
        @Override
        public void run() {
          if (count >= maximumAttempts) {
            this.future.cancel(true);
            System.out.println("Cancelling the task with id :"+id+" after count :"+count);
            return;
          count++;
          this.runnable.run();
         * Return the number of attempt.
         * @return
        public int getCount() {
          return count;
      private void submitTaskForContinuousExecution(Runnable runnable, String id){
        int numOfAttempts = 10;
        MyRunnableTask runnableTask = new MyRunnableTask(runnable, numOfAttempts, id);
        int interval = 1;
        ScheduledFuture<?> scheduleWithFixedDelay = this.scheduleWithFixedDelay(runnableTask, 0, TimeUnit.SECONDS.toMillis(interval), TimeUnit.MILLISECONDS);
        if(id != null) {
          /*System.out.println("Submitted the task for continuous execution for the ticket id :"+id+"  with maximum attempts : "+numOfAttempts
              + " and interval : "+ interval);*/
          runnableTask.future = scheduleWithFixedDelay;
       * Creates an Executor Service to provide customized execution for tasks to be scheduled.
       * @param threadName is the name that shows in logs.
       * @param maximumThreads is the number of threads can be created.
       * @param rejectedExecutionHandler is if the Queue reaches it's maximum capacity and all the executor gives
       * the tasks to rejectedExecutionHandler.
      public TestScheduledExecutorService(String threadName, int maximumThreads, RejectedExecutionHandler rejectedExecutionHandler) {
        this.executor = createExecutor(threadName, maximumThreads, rejectedExecutionHandler);
      protected ThreadPoolExecutor createExecutor(String threadName, int minimumThreads, RejectedExecutionHandler rejectedExecutionHandler) {
        ThreadPoolExecutor threadPoolExecutor = new ScheduledThreadPoolExecutor(minimumThreads)
          @Override
          protected void beforeExecute(Thread t, Runnable r) {
            TestScheduledExecutorService.this.beforeExecute(t, r);
            this.purge();
          @Override
          protected void afterExecute(Runnable r, Throwable t) {
            TestScheduledExecutorService.this.afterExecute(r, t);
        if(rejectedExecutionHandler != null) {
          threadPoolExecutor.setRejectedExecutionHandler(rejectedExecutionHandler);
        }else{
          threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolExecutor.setThreadFactory(new TestThreadFactory(threadName, threadPoolExecutor));
        threadPoolExecutor.setKeepAliveTime(120, TimeUnit.SECONDS);
        threadPoolExecutor.allowCoreThreadTimeOut(true);
        return threadPoolExecutor;
       * Executes the task repeatedly with the given delay
       * @param task
       * @param initialDelay
       * @param delay
       * @param unit
       * @return
      public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, int initialDelay, long delay, TimeUnit unit) {
        return ((ScheduledThreadPoolExecutor)executor).scheduleWithFixedDelay(task, initialDelay, delay, unit);
       * To provide threads with specific features.
      protected static class TestThreadFactory implements ThreadFactory {
        private ThreadFactory threadFactory = Executors.defaultThreadFactory();
        private ThreadPoolExecutor threadPoolExecutor;
        private String groupName;
        public TestThreadFactory(String groupName, ThreadPoolExecutor threadPoolExecutor) {
          this.groupName = groupName;
          this.threadPoolExecutor = threadPoolExecutor;
        @Override
        public Thread newThread(Runnable r) {
          Thread thread = threadFactory.newThread(r);
          int activeCount = this.threadPoolExecutor.getPoolSize();
          activeCount++;
          thread.setName(this.groupName+"-"+activeCount);
          thread.setDaemon(true);
          return thread;
       * Performs initialization tasks before starting this thread.
       * @param thread
       * @param runnable
      protected void beforeExecute(Thread thread, Runnable runnable){
       * Performs tasks after execution of this runnable.
       * @param thread
       * @param runnable
      protected void afterExecute(Runnable runnable, Throwable t){
       * Initiates an orderly shutdown in which previously submitted
       * tasks are executed, but no new tasks will be
       * accepted. Invocation has no additional effect if already shut
       * down.
      public void shutdown() {
        if(this.executor != null) {
          Log.notice(CLASS_NAME, "shutdown", "Shutting down Executor Service");
          this.executor.shutdown();
       * Attempts to stop all actively executing tasks, halts the
       * processing of waiting tasks, and returns a list of the tasks
       * that were awaiting execution. These tasks are drained (removed)
       * from the task queue upon return from this method.
       * <p>There are no guarantees beyond best-effort attempts to stop
       * processing actively executing tasks.  This implementation
       * cancels tasks via {@link Thread#interrupt}, so any task that
       * fails to respond to interrupts may never terminate.
      public List<Runnable> shutdownNow() {
       if(this.executor != null) {
         Log.notice(CLASS_NAME, "shutdownNow", "Immediately shutting down Executor Service");
         try {
          return this.executor.shutdownNow();
        } catch (Exception e) {
          Log.notice(CLASS_NAME, "shutdownNow", e.getMessage());
       return Collections.emptyList();
       * Returns a Future for the given runnable task.
      public Future<?> submit(Runnable runnable) {
        if(this.executor != null) {
          return this.executor.submit(runnable);
        return null;
    Is there any possibility for the continuous execution or not?

    I have a Customized implementation for ScheduledThreadPoolExecutor using which I am trying to execute a task for continuous execution. The problem I have faced here with the implementation is, some tasks executed continuously where as two of them are not respecting the delay and executed continuously. I am using the scheduleWithFixedDelay method.
    Even I have tried reproducing, but I couldn't.
    Here is my customized implementation.
    package com.portware.utils.snapmarketdata.test;
    import java.util.Collections;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Set;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.RejectedExecutionHandler;
    import java.util.concurrent.ScheduledFuture;
    import java.util.concurrent.ScheduledThreadPoolExecutor;
    import java.util.concurrent.ThreadFactory;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.atomic.AtomicInteger;
    import com.indigo.utils.Log;
    * To schedule the tasks in timely manner.
    public class TestScheduledExecutorService  {
      private static String CLASS_NAME = TestScheduledExecutorService.class.getName();
      protected final ThreadPoolExecutor executor;
      static int totalCount = 0;
      public static void main(String[] args) throws InterruptedException {
        TestScheduledExecutorService executorService = new TestScheduledExecutorService("Test", 10, null);
        final AtomicInteger integer = new AtomicInteger();
        final Set<Integer> testSet = new HashSet<Integer>();
        for (int i = 0; i < 10; i++) {
          testSet.add(i);
        Iterator<Integer> iterator = testSet.iterator();
        synchronized (testSet) {
        while(iterator.hasNext()) {
          integer.set(iterator.next());
          executorService.submitTaskForContinuousExecution(new Runnable() {
          @Override
          public void run() {
              System.out.println(Thread.currentThread().getName()+" Hello : "+integer.get() + " count value is:"+totalCount++);
        }, integer.toString());
        while (true) {
          synchronized (TestScheduledExecutorService.class) {
            TestScheduledExecutorService.class.wait();
      private static class MyRunnableTask implements Runnable{
        ScheduledFuture<?> future;
         * The task to be run.
        private Runnable runnable;
         * The number of attempt.
        private int count;
         * Maximum attempts configured under TCA configuration.
        private int maximumAttempts;
        private String id;
        public MyRunnableTask(Runnable runnable, int maximumAttempts, String id) {
          this.runnable = runnable;
          this.maximumAttempts = maximumAttempts;
          this.id = id;
        @Override
        public void run() {
          if (count >= maximumAttempts) {
            this.future.cancel(true);
            System.out.println("Cancelling the task with id :"+id+" after count :"+count);
            return;
          count++;
          this.runnable.run();
         * Return the number of attempt.
         * @return
        public int getCount() {
          return count;
      private void submitTaskForContinuousExecution(Runnable runnable, String id){
        int numOfAttempts = 10;
        MyRunnableTask runnableTask = new MyRunnableTask(runnable, numOfAttempts, id);
        int interval = 1;
        ScheduledFuture<?> scheduleWithFixedDelay = this.scheduleWithFixedDelay(runnableTask, 0, TimeUnit.SECONDS.toMillis(interval), TimeUnit.MILLISECONDS);
        if(id != null) {
          /*System.out.println("Submitted the task for continuous execution for the ticket id :"+id+"  with maximum attempts : "+numOfAttempts
              + " and interval : "+ interval);*/
          runnableTask.future = scheduleWithFixedDelay;
       * Creates an Executor Service to provide customized execution for tasks to be scheduled.
       * @param threadName is the name that shows in logs.
       * @param maximumThreads is the number of threads can be created.
       * @param rejectedExecutionHandler is if the Queue reaches it's maximum capacity and all the executor gives
       * the tasks to rejectedExecutionHandler.
      public TestScheduledExecutorService(String threadName, int maximumThreads, RejectedExecutionHandler rejectedExecutionHandler) {
        this.executor = createExecutor(threadName, maximumThreads, rejectedExecutionHandler);
      protected ThreadPoolExecutor createExecutor(String threadName, int minimumThreads, RejectedExecutionHandler rejectedExecutionHandler) {
        ThreadPoolExecutor threadPoolExecutor = new ScheduledThreadPoolExecutor(minimumThreads)
          @Override
          protected void beforeExecute(Thread t, Runnable r) {
            TestScheduledExecutorService.this.beforeExecute(t, r);
            this.purge();
          @Override
          protected void afterExecute(Runnable r, Throwable t) {
            TestScheduledExecutorService.this.afterExecute(r, t);
        if(rejectedExecutionHandler != null) {
          threadPoolExecutor.setRejectedExecutionHandler(rejectedExecutionHandler);
        }else{
          threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolExecutor.setThreadFactory(new TestThreadFactory(threadName, threadPoolExecutor));
        threadPoolExecutor.setKeepAliveTime(120, TimeUnit.SECONDS);
        threadPoolExecutor.allowCoreThreadTimeOut(true);
        return threadPoolExecutor;
       * Executes the task repeatedly with the given delay
       * @param task
       * @param initialDelay
       * @param delay
       * @param unit
       * @return
      public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, int initialDelay, long delay, TimeUnit unit) {
        return ((ScheduledThreadPoolExecutor)executor).scheduleWithFixedDelay(task, initialDelay, delay, unit);
       * To provide threads with specific features.
      protected static class TestThreadFactory implements ThreadFactory {
        private ThreadFactory threadFactory = Executors.defaultThreadFactory();
        private ThreadPoolExecutor threadPoolExecutor;
        private String groupName;
        public TestThreadFactory(String groupName, ThreadPoolExecutor threadPoolExecutor) {
          this.groupName = groupName;
          this.threadPoolExecutor = threadPoolExecutor;
        @Override
        public Thread newThread(Runnable r) {
          Thread thread = threadFactory.newThread(r);
          int activeCount = this.threadPoolExecutor.getPoolSize();
          activeCount++;
          thread.setName(this.groupName+"-"+activeCount);
          thread.setDaemon(true);
          return thread;
       * Performs initialization tasks before starting this thread.
       * @param thread
       * @param runnable
      protected void beforeExecute(Thread thread, Runnable runnable){
       * Performs tasks after execution of this runnable.
       * @param thread
       * @param runnable
      protected void afterExecute(Runnable runnable, Throwable t){
       * Initiates an orderly shutdown in which previously submitted
       * tasks are executed, but no new tasks will be
       * accepted. Invocation has no additional effect if already shut
       * down.
      public void shutdown() {
        if(this.executor != null) {
          Log.notice(CLASS_NAME, "shutdown", "Shutting down Executor Service");
          this.executor.shutdown();
       * Attempts to stop all actively executing tasks, halts the
       * processing of waiting tasks, and returns a list of the tasks
       * that were awaiting execution. These tasks are drained (removed)
       * from the task queue upon return from this method.
       * <p>There are no guarantees beyond best-effort attempts to stop
       * processing actively executing tasks.  This implementation
       * cancels tasks via {@link Thread#interrupt}, so any task that
       * fails to respond to interrupts may never terminate.
      public List<Runnable> shutdownNow() {
       if(this.executor != null) {
         Log.notice(CLASS_NAME, "shutdownNow", "Immediately shutting down Executor Service");
         try {
          return this.executor.shutdownNow();
        } catch (Exception e) {
          Log.notice(CLASS_NAME, "shutdownNow", e.getMessage());
       return Collections.emptyList();
       * Returns a Future for the given runnable task.
      public Future<?> submit(Runnable runnable) {
        if(this.executor != null) {
          return this.executor.submit(runnable);
        return null;
    Is there any possibility for the continuous execution or not?

  • Trying to update UI with from another thread

    Hi,
    I start a JavaFX application from another class, and then I want to modify UI components from it. I have been trying to use Platform.runLater to do it.
    But the GUI hangs initially (doesnt display anything) for the first 5 seconds (sleep time) and then modifies and shows it.
    I want to display the GUI at first, and then after 5 seconds the GUI should update with the message, but with the below code it just hangs first and displays everything after 5seconds.
    Here sampleGUI is a a javafx app with text fields in it.
    +public class StartGame extends Application {+
    +@Override+
    +public void start(Stage stage) throws Exception {+
    final sampleGUI gui = new sampeGUI();
    gui.start(stage);
    +Platform.runLater(new Runnable() {+
    +@Override+
    +public void run() {+
    +try {+
    System.out.println("Sleeping now...");
    Thread.sleep(5000);
    System.out.println("Sleep over!");
    gui.updateText("New message");
    +} catch (InterruptedException ex) {+
    System.out.println("exception" ex);+
    +}+
    +}+
    +});+
    +}+
    +}+

    Platform.runLater(new Runnable() {
      @Override
      public void run() {
    });causes the Runnable's run method to be executed on the FX Application Thread. Since you put Thread.sleep(5000) inside your Runnable's run method, the sleep happens on the FX Application Thread.
    The call to runLater(...) can be invoked from any thread, including the FX Application Thread.
    So if you are not in the FX Application thread, you want to do:
    // any long-running task, for example
    System.out.println("Sleeping now");
    Thread.sleep(5000);
    System.out.println("Sleep over");
    Platform.runLater(new Runnable() {
      @Override
      public void run() {
        // update UI:
        gui.updateText("New Message");
    });If you are on the FX Application thread, which is the case in your Application.start(...) method, you need to create a new thread to execute your long-running code. You can do this "by hand", creating a Thread and a Runnable for it to execute, but it's probably better to use the JavaFX concurrency API, which has lots of useful hooks for updating the UI on the FX Application Thread.
    In this case, the code would look like this:
    public class StartGame extends Application {
      @Override
      public void start(Stage stage) throws Exception {
        final SampleGUI gui = new SampleGUI();
        gui.start();
        final Task<String> waitingTask = new Task<String>() {
          @Override
          public String call() throws Exception {
            System.out.println("Sleeping");
            Thread.sleep(5000);
            System.out.println("Sleep over!");
            return "New Message" ;
        waitingTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
          @Override
          public void handle(WorkerStateEvent event) {
            gui.updateMessage(waitingTask.getValue());
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(waitingTask);
    }There are (probably dozens of) other ways to use a Task to do this. See the [url http://docs.oracle.com/javafx/2/api/javafx/concurrent/Task.html]API docs for Task for more.

  • Thread executer

    i have a list of task that is currently running sequentially.
    each task is independent of one another.
    what i want to do is to execute these tasks in threads (each task run in a thread)
    but i want to limit the number of thread running (ie. only five thread may running..when one is finished, another thread may start running untill all thread in a list is done)
    Is there some class that let me do this?
    if there isn't any, can someone tell me what this thread problem be called (ie..countdown latch, blocking queue)
    so i can google and try to implement it

    You can try things like.
            ExecutorService executor = Executors.newFixedThreadPool(5);
            Future future = executor.submit(new Runnable() {
                public void run() {
            future.get();
            Future<String> futureCall = executor.submit(new Callable<String>() {
                public String call() throws Exception {
                    return "Hello world";
            String result = futureCall.get();

  • Singleton with timeout

    Hi!
    I have to implement Singleton pattern, but I have the following restriction: The getInstance() method should not stop the entire application.
    I wrote the following code, to achieve my objective:
    public class ServiceProvider {
        private static Service service;
        private static final PrivateClass singletonProvider = new PrivateClass();
        private ServiceProvider() {}
        public static synchronized Service getInstance() throws MyException {
            if (service == null) {
                Thread thread = new Thread(singletonProvider);
                thread.start();
                try {
                    // Ten seconds for the construction of the service field.
                    Thread.sleep(10000);
                } catch (InterruptedException ex) {
                    throw new MyException("InterruptedException!!!", ex);
                // Is the verification based on Thread.isAlive() safe?
                // I am not sure. Please, tell me.
                if (!thread.isAlive()) {
                    if (service == null) {
                        throw new MyException("Service is still not available");
                    } else {
                        return service;
                } else {
                    throw new MyException("Service is still not available");
            } else {
                return service;
        // Using a private class I do not need to expose the public run() method.
        private static class PrivateClass implements Runnable {
            private PrivateClass() {}
            private synchronized Service defineInstance() throws MyException {
                if (service == null) {
                    service = new Service();
                return service;
            public synchronized void run() {
                try {
                    singletonProvider.defineInstance();
                } catch (Exception e) {
                    e.printStackTrace();
    public class Service {
        public Service() throws MyException {
            try {
                // Simulating a problem: the constructor is taking 20 seconds to be finished.
                Thread.sleep(20000);
            } catch (InterruptedException ex) {
                throw new MyException("InterruptedException in the Service constructor", ex);
        public void method() {
    }I am just not sure if the verification based on Thread.isAlive() is safe.
    Thanks!!!

    malcolmmc wrote:
    This sounds all very familiar. This is an occasion to use wait and notify to synchronize with your background thread. For one thing, the way you've written it, the caller to getInstance() will wait 10 seconds even if the service instance is loaded much faster than that.Yes... I tried what you are suggesting, but the problem is that using wait and notify I have to lock the PrivateClass field of the ServiceProvider class. So, since the fields should be locked, the call to the Service constructor will also be locked, and then I always have to wait the constructor finishes, no matter how I implement the logic of wait and notify.
    So instead of sleep(10000L) use wait(10000L). Then when your loader sets the instance variable it calls notify on the same monitor. This will wake the main thread up if it's waiting.
    You also need to deal with the case where getInstance is called a second time either when the first call to getInstance() is waiting, or after the first call has given up.I did the following solution instead. It works fine:
    public class ServiceProvider {
        private static Service service;
        private static final PrivateClass privateClass = new PrivateClass();
        private ServiceProvider() {}
        public static synchronized Service getInstance() throws MyException {
            if (service == null) {
                ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
                AnotherPrivateClass anotherPrivateClass = new AnotherPrivateClass();
                Future future = executor.submit(anotherPrivateClass);
                try {
                    // Ten seconds for the construction of the service field.
                    future.get(10000,TimeUnit.MILLISECONDS);
                } catch (TimeoutException ex) {
                    throw new MyException("Service is still not available");
                } catch (ExecutionException ex) {
                    throw new MyException("Service is still not available");
                } catch (InterruptedException ex) {
                    throw new MyException("Service is still not available");
                } finally {
                    executor.shutdown();
                // Is the verification based on Thread.isAlive() safe?
                // I am not sure. Please, tell me.
                if (!anotherPrivateClass.thread.isAlive()) {
                    if (service == null) {
                        throw new MyException("Service is still not available");
                    } else {
                        return service;
                } else {
                    throw new MyException("Service is still not available");
            } else {
                return service;
        private static class AnotherPrivateClass implements Runnable {
            private Thread thread;
            private AnotherPrivateClass() {
                this.thread = new Thread(privateClass);
            public synchronized void run() {
                thread.start();
                try {
                    synchronized (privateClass) {
                        while (!privateClass.done) {
                            privateClass.wait();
                        if (service == null) {
                            privateClass.done = false;
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
        // Using a private class I do not need to expose the public run() method.
        private static class PrivateClass implements Runnable {
            boolean done = false;
            private PrivateClass() {}
            private synchronized void defineInstance() throws MyException {
                if (service == null) {
                    service = new Service();
            public synchronized void run() {
                try {
                    privateClass.defineInstance();
                } catch (Exception e) {
                    e.printStackTrace();
                done = true;
                this.notify();
    }

  • CompletionService for asynchronous recurring tasks

    Hi everybody,
    I have the following use case: I want to poll and convert newsfeeds.
    Which means that my job consists of two different tasks:
    1. The polling
    Basically this means, that I need to download an xml document. This should be done in a scheduled way like "Download this feed
    every n hours". So it is an asynchronous recurring task, that is parametrized with the polling interval specific to each thread.
    2 The conversion
    Here the newsfeed downloaded before should be converted into a new format.
    My idea was not, to achieve this via a ExecutorCompletionService. That would work well, if it weren't for the scheduling and recurrent execution:
    You can initialize an ExecutorCompletionService with a ScheduledThreadPoolExecutor as its Executor. But since the ExecutorCompletionService only uses the Executor interface to do its job, I cannot achieve the individual scheduling/recurrent execution
    of my download-task like that.
    I am currently considering to extend ExecutorCompletionService and override the submit method to handle the scheduling, according to the feed specific interval. Problem here: I do not know how the queuing is implemented in ExecutorCompletionService and how to deal with that.
    Please shed some light into this (admittedly very specific) problem :-)
    Edited by: er4z0r on 20.01.2010 17:50

    O.K. I tried to implement a CompletionService for scheduled recurring tasks. And as a word of warning: I did NOT succeed. Don't try this at home ;-)
    I did this by extending the CompletionService interface so that it provides scheduling-methods:
    package org.example.demo.scheduledcompletion;
    import java.util.concurrent.Callable;
    import java.util.concurrent.CompletionService;
    import java.util.concurrent.ScheduledFuture;
    import java.util.concurrent.TimeUnit;
    * Extends the CompletionService to allow the usage of scheduled tasks
    * @author tbender
    public interface ScheduledCompletionService<V> extends CompletionService<V> {
         ScheduledFuture<?> submitAtFixedRate(Callable<V> command, long initialDelay, long period, TimeUnit unit);
         ScheduledFuture<?> submitWithFixedDelay(Callable<V> command,long initialDelay, long delay, TimeUnit unit);
    }I then added a class implementing this interface and internally using a ScheduledExectuorService instead of an normal Executor like ExecutorCompletionService. I took most of the code from ExecutorCompletionService :
    package org.example.demo.scheduledcompletion;
    import java.util.concurrent.BlockingQueue;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.Future;
    import java.util.concurrent.FutureTask;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.ScheduledFuture;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    * Immplementation of ScheduledCompletionService using a
    * ScheduledExecutorService
    * This class is supposed to provide a CompletionService for asynchronous
    * recurring tasks. After using one of the schedule methods to schedule a
    * recurring task, a Future representing the task will be available once the
    * task is done.
    * @author tbender
    public class ScheduledExecutorCompletionService<V> implements
              ScheduledCompletionService<V> {
         private final ScheduledExecutorService executor;
         private final BlockingQueue<Future<V>> completionQueue;
         private final Log log;
          * FutureTask extension to enqueue upon completion
          * @author tbender
         public class QueueingFuture extends FutureTask<V> {
               * (non-Javadoc)
               * @see java.util.concurrent.FutureTask#run()
              @Override
              public void run() {
                   log.debug("run called");
                   super.run();
                   log.debug("Size of Completionqueue before adding this task: " + completionQueue.size());
                   completionQueue.add(this);
                   log.debug("Size of Completionqueue after adding this task: " + completionQueue.size());
              @Override
              public boolean cancel(boolean mayInterruptIfRunning) {
                   log.debug("cancel called");
                   boolean canceled = super.cancel(mayInterruptIfRunning);
                   if (canceled) {
                        log.debug("Successfully canceled.");
                   } else {
                        log.warn("No succcess canceling the job");
                   return canceled;
              @Override
              public V get() throws InterruptedException, ExecutionException {
                   log.debug("get called");
                   return super.get();
              @Override
              public V get(long timeout, TimeUnit unit) throws InterruptedException,
                        ExecutionException, TimeoutException {
                   log.debug("get called");
                   return super.get(timeout, unit);
              @Override
              public boolean isCancelled() {
                   log.debug("isCancelled called");
                   return super.isCancelled();
              @Override
              public boolean isDone() {
                   log.debug("isDone called");
                   return super.isDone();
              @Override
              protected boolean runAndReset() {
                   log.debug("runAndReset called");
                   return super.runAndReset();
              @Override
              protected void set(V v) {
                   log.debug("set called");
                   super.set(v);
              @Override
              protected void setException(Throwable t) {
                   log.debug("set exception called");
                   super.setException(t);
              public QueueingFuture(Callable<V> callable) {
                   super(callable);
                   log.debug("creating QueueingFuture for callable: " + callable);
              public QueueingFuture(Runnable t, V result) {
                   super(t, result);
                   log.debug("creating QueueingFuture for runnable: " + t
                             + " and result " + result);
              @Override
              protected void done() {
                   log.debug("done called");
          * @param executor
         public ScheduledExecutorCompletionService(ScheduledExecutorService executor) {
              super();
              if (executor == null) {
                   throw new IllegalArgumentException("You must specify an executor");
              this.log = LogFactory.getLog(this.getClass());
              this.executor = executor;
              this.completionQueue = new LinkedBlockingQueue<Future<V>>();
          * @param executor
          * @param completionQueue
         public ScheduledExecutorCompletionService(
                   ScheduledExecutorService executor,
                   BlockingQueue<Future<V>> completionQueue) {
              super();
              if (executor == null || completionQueue == null) {
                   throw new IllegalArgumentException();
              this.log = LogFactory.getLog(this.getClass());
              this.executor = executor;
              this.completionQueue = completionQueue;
         @Override
         public ScheduledFuture<?> submitAtFixedRate(Callable<V> command,
                   long initialDelay, long period, TimeUnit unit) {
              if (command == null) {
                   throw new IllegalArgumentException();
              log.debug("Submitting new " + command.getClass().getName()
                        + " at fixed rate of " + period + " " + unit);
              QueueingFuture f = new QueueingFuture(command);
              return this.executor.scheduleAtFixedRate(f, initialDelay, period, unit);
         @Override
         public ScheduledFuture<?> submitWithFixedDelay(Callable<V> command,
                   long initialDelay, long delay, TimeUnit unit) {
              if (command == null) {
                   throw new IllegalArgumentException();
              log.debug("Submitting new " + command.getClass().getName()
                        + " at fixed delay of " + delay + " " + unit);
              QueueingFuture f = new QueueingFuture(command);
              return this.executor.scheduleWithFixedDelay(f, initialDelay, delay,
                        unit);
         @Override
         public Future<V> poll() {
              return this.completionQueue.poll();
         @Override
         public Future<V> poll(long timeout, TimeUnit unit)
                   throws InterruptedException {
              return this.completionQueue.poll(timeout, unit);
         @Override
         public Future<V> submit(Callable<V> task) {
              if (task == null) {
                   throw new IllegalArgumentException();
              log.debug("Submitting new " + task.getClass().getName());
              QueueingFuture f = new QueueingFuture(task);
              this.executor.submit(f);
              return f;
         @Override
         public Future<V> submit(Runnable task, V result) {
              if (task == null) {
                   throw new IllegalArgumentException();
              log.debug("Submitting new " + task.getClass().getName());
              QueueingFuture f = new QueueingFuture(task, result);
              this.executor.submit(f);
              return f;
         @Override
         public Future<V> take() throws InterruptedException {
              return this.completionQueue.take();
    }See next post for tests.

  • Mail program doubt

    i have used this program for sending mail through SAP.It has two options.First for sending as an html attachement,second for plain text inline with the body of the message.Actually i need the message in html format inline with the body of the message itself(not as an attachement)
    In simple words the body of the message want to be in html format,not an attachement..
    *& Report  ZMAIL                                                       *
    report  zmail                                   .
    tables: soos1.
    *type-pools: sbdst.
    parameters: report like varis-report obligatory.
    parameters: variant like varis-variant obligatory.
    parameters:reptitle like soos1-recrem  obligatory.
    select-options: recnam for soos1-recrem  obligatory.
    *{   INSERT         EDPK900415                                        1
    selection-screen skip 1.
    selection-screen begin of block b1 with frame title text-001.
    selection-screen begin of line.
    parameters: r1 radiobutton group g1.
    selection-screen comment:5(40) text-003 for field r1.
    selection-screen position 35.
    selection-screen end of line.
    selection-screen begin of line.
    parameters: r2 radiobutton group g1.
    selection-screen comment: 5(40) text-002 for field r2.
    selection-screen end of line.
    selection-screen end of block b1.
    *}   INSERT
    data: begin of html_tab occurs 0.
            include structure w3html.
    data: end of html_tab.
    data : it_pack_list  like soxpl occurs 0 with header line.
    data: begin of html_tab_converted occurs 0,
                line(255) type c,
              end of html_tab_converted.
    data:  listobject like abaplist occurs 20 with header line.
    data:  abap_list like abaplist occurs 20 with header line.
    data: icontab(32) occurs 10 with header line.
    data: lineno type i, length type i, size type i,
          l_filename like rlgrap-filename.
    data: icon_wa  type icon,
          internal type icon-internal,
          existing type c.
    data: my_bds type ref to cl_bds_document_set,
          key    type sbdst_object_key,
          files  type sbdst_files,
          wa     type bapifiles.
    data: filename type string,
          filefilter type string,
          path type string,
          fullpath type string.
    data: user_action type i.
    data: cur_guicopdepage(4) type c.
    data: gui_codepage(4) type n,        " added for message 500824
          is_unicode type rststype-sel_ok.
    data: convert_output type xstring,
          convert_buffer type xstring.
    data i type i.
    data tablength type i.
    data dummy type i.
    data list_index like  sy-lsind .
    data begin of new_pack_list occurs 10.
            include structure soxpl.
    data end of new_pack_list.
    data : owner like soud-usrnam.
    data: fg_sysdli like sonv-flag,
    fg_folrg like soxdl-folrg,
    dli_tab_save like soxdl occurs 20 with header line.
    data: rec_count like sy-tabix.
    data: object_type like sood-objtp value 'RAW'.
    data: object_hd_change like sood1 occurs 0 with header line.
    data: objcont like soli occurs 0 with header line.
    data: attcont_tab like soli occurs 0 with header line.
    data: atthead_tab like soli  occurs 0 with header line.
    data  so_ali like soli occurs 100 with header line.
    data  document_data like sodocchgi1.
    data  msg_text(80) type c.           "Message text
    data:  length type i, size type i.
    data  profile like soprd.
    data  subrc like sy-subrc value 0.
    data  so_ali_hex type standard table of solix.   "note 604603
    data: objpara like selc occurs 0 with header line.
    data: objparb like soop1 occurs 0 with header line.
    data: receivers like soos1 occurs 0 with header line.
    *data: receivers like soos5 occurs 0 with header line.
    data: r_dliq type c. "Shared Distrbution List
    data: r_dlip type c. "Private Distrbution list
    data: rep_title(50) type c. "Report Title
    data : begin of dis_lst occurs 10. "Internal table to store DL
            include structure sodm1.
    data : end of dis_lst.
    data : begin of listtab occurs 100. "Internal Table for List CONTAINER
            include structure abaplist.
    data : end of listtab.
    data : begin of downtab occurs 1,
    line(255),
    end of downtab.
    data ls_cnt type n.
    data:begin of it_mailid occurs 0,
         mailid(100), "  TYPE ZSENDINT_MAILID-MAILID,
         end of it_mailid.
    data c1.
    c1 = ' '.
    shift reptitle left deleting leading c1.
    *SELECT MAILID FROM ZSENDINT_MAILID INTO TABLE IT_MAILID WHERE SUBJECT = REPTITLE AND FLAG <> 'X'.
    "IF SY-SUBRC = 0.
    "CLEAR RECNAM.
    "REFRESH RECNAM.
    "LOOP AT IT_MAILID.
    "MOVE 'I' TO RECNAM-SIGN.
    "MOVE 'EQ' TO RECNAM-OPTION.
    "MOVE IT_MAILID-MAILID TO RECNAM-LOW.
    "APPEND RECNAM.
    "ENDLOOP.
    "ENDIF.
    *S.KARTHIKRAJA 07.10.2006
    call function 'LIST_FREE_MEMORY'
      tables
        listobject = listobject
      exceptions
        others     = 1.
    submit (report)
    using selection-set variant
                     exporting list to memory and return.
    import listobject from memory id '%_LIST'.
    if listobject[] is initial.
      exit.
    endif.
    call function 'WWW_HTML_FROM_LISTOBJECT'
           exporting
                  REPORT_NAME   =
                template_name = 'WEBREPORTING_REPORT'
           tables
                html          =  html_tab
                listobject    =  listobject
                listicons     =  icontab.
    call function 'LIST_TO_ASCI'
      exporting
        list_index         = -1
      tables
        listasci           = downtab
        listobject         = listobject
      exceptions
        empty_list         = 1
        list_index_invalid = 2
        others             = 3.
    call function 'TABLE_COMPRESS'       "Schneller Tabellencopy
          tables
               in         = listobject
               out        = so_ali.      "note 604603
               out        = so_ali_hex.   "note 604603
    call function 'SO_SOLIXTAB_TO_SOLITAB'           "note 604603
         exporting
              ip_solixtab = so_ali_hex[]
         importing
              ep_solitab  = so_ali[].
    call function 'SO_DLI_LIST_READ_XDL'
    exporting
    private = 'X'
    public = 'X'
    subscript = 'X'
    tables
    dli_display_tab = dli_tab_save
    exceptions
    communication_failure = 1
    dl_list_no_entries = 2
    owner_not_exist = 3
    system_failure = 4
    x_error = 5
    parameter_error = 6
    others = 7.
    call function 'SO_DLI_EXPAND'
    exporting
    system_dli = fg_sysdli
    convert = 'X'
    tables
    member = dis_lst
    objpara = objpara
    objparb = objparb
    exceptions
    active_user_not_exist = 1
    communication_failure = 2
    component_not_available = 3
    dl_name_not_exist = 4
    folder_not_exist = 5
    folder_no_authorization = 6
    forwarder_not_exist = 7
    object_not_exist = 8
    object_no_authorization = 9
    operation_no_authorization = 10
    owner_not_exist = 11
    parameter_error = 12
    recurrency_exist = 13
    substitute_not_active = 14
    substitute_not_defined = 15
    system_failure = 16
    x_error = 17
    others = 18.
    refresh receivers.
    clear receivers.
    move sy-datum  to receivers-rcdat .
    move sy-uzeit  to receivers-rctim.
    refresh object_hd_change.
    object_hd_change-objla = sy-langu. "Language
    object_hd_change-objcp = ' '. " Object can be changed byUSER
    object_hd_change-objsns = 'F'. " Msg Sensitivity private orbusiness
    object_hd_change-objdes = reptitle.
    object_hd_change-objnam = object_hd_change-objdes.
    append object_hd_change.
    if r1 = 'X'.
      move html_tab[] to objcont[].
    else.
      move downtab[] to objcont[].
    endif.
    describe table objcont lines i.
    it_pack_list-head_start = 1.
    it_pack_list-head_num = 0.
    it_pack_list-body_start = 1.
    it_pack_list-body_num = i.
    it_pack_list-OBJTP = 'RAW'.
    move variant to it_pack_list-objnam.
    move variant to it_pack_list-objdes.
    move 'HTM' to it_pack_list-file_ext.
    append it_pack_list.
    loop at html_tab.
      call function 'SCP_TRANSLATE_CHARS'
        exporting
          inbuff           = html_tab
          outcode          = gui_codepage
          csubst           = 'X'
          substc_space     = 'X'
          substc           = '00035'
        importing
          outbuff          = convert_output
        exceptions
          invalid_codepage = 1
          internal_error   = 2
          cannot_convert   = 3
          fields_bad_type  = 4
          others           = 5.
      concatenate convert_buffer convert_output into convert_buffer in
      byte mode.
    endloop.
    i = 0.
    describe field html_tab_converted length tablength in byte mode.
    while i < xstrlen( convert_buffer ).
      dummy = xstrlen( convert_buffer ) - i.
      if tablength > dummy.
        html_tab_converted-line = convert_buffer+i(dummy).
      else.
        html_tab_converted-line = convert_buffer+i(tablength).
      endif.
      i = i + tablength.
      append html_tab_converted.
    endwhile.
    receivers-sel = 'X'.
    receivers-sndex = ' '. "
    receivers-sndpri = '1'. "Priority of the message
    receivers-deliver = ' '.
    receivers-not_deli = ' '.
    receivers-read = ' '.
    receivers-recnam = 'U-'.
    receivers-mailstatus = 'E'.
    receivers-sortclass = '5'.
    receivers-recesc = 'U'. " U means Internet Address
    receivers-SAP_BODY = 'X'.
    receivers-sndart = 'INT'.
    loop at recnam.
      receivers-adr_name = recnam-low.
      receivers-recextnam = recnam-low.
      append receivers.
    endloop.
    owner = sy-uname.
    if r1  = 'X'.
      call function 'SO_OBJECT_SEND'
      exporting
    object_hd_change = object_hd_change
      object_type = object_type
      outbox_flag = 'X'
      owner = owner
      sender = sy-uname
      tables
      receivers = receivers
    packing_list = it_pack_list
      att_cont = objcont
      att_head = atthead_tab
      exceptions
      active_user_not_exist = 1
      communication_failure = 2
      component_not_available = 3
      folder_not_exist = 4
      folder_no_authorization = 5
      forwarder_not_exist = 6
      note_not_exist = 7
      object_not_exist = 8
      object_not_sent = 9
      object_no_authorization = 10
      object_type_not_exist = 11
      operation_no_authorization = 12
      owner_not_exist = 13
      parameter_error = 14
      substitute_not_active = 15
      substitute_not_defined = 16
      system_failure = 17
      too_much_receivers = 18
      user_not_exist = 19
      x_error = 20
      others = 21.
    else.
      call function 'SO_OBJECT_SEND'
       exporting
      object_hd_change = object_hd_change
       object_type = object_type
       outbox_flag = 'X'
       owner = owner
       sender = sy-uname
       tables
       objcont = objcont
       receivers = receivers
       exceptions
       active_user_not_exist = 1
       communication_failure = 2
       component_not_available = 3
       folder_not_exist = 4
       folder_no_authorization = 5
       forwarder_not_exist = 6
       note_not_exist = 7
       object_not_exist = 8
       object_not_sent = 9
       object_no_authorization = 10
       object_type_not_exist = 11
       operation_no_authorization = 12
       owner_not_exist = 13
       parameter_error = 14
       substitute_not_active = 15
       substitute_not_defined = 16
       system_failure = 17
       too_much_receivers = 18
       user_not_exist = 19
       x_error = 20
       others = 21.
    endif.
    commit work.
    call function 'SO_DEQUEUE_UPDATE_LOCKS'.

    i have not gone thru your source code fully.
    maintain the text in Tcode SO10.
    use the fn module READTEXT* to read the contents of the text.
    cheers
    jayanthi.K

  • How to execute report in Background from Dialog process?

    How, or what is the best way, to lauch an executable program (report) into the background from a dialog program (dynpro)?
    <b>Example:</b>  The SUBMIT...AND RETURN still executes the called program before it returns control to the calling program.  I just want the report to be kicked off and the dialog to continue as normal.  I do not want the report execution time to affect the dialog process.
    Thanks in advance for your time.

    Hi Nablan, I'm also trying to do parallel processing and created a function module that kicks of another report program.
    However, the process doesn't seem to work. The Main program runs from start to finish but the called program in the function module doesn't seem to run. When I used the option STARTING NEW TASK task name the code ran but in the foreground. I don't want to use this option as it runs in the foreground and SAP limits one to six sessions. Is there something I'm missing in the attributes of the function module I created. Currently the attributes are: Processing type Remote enable module and it's set to start immediately. I had used Normal function module initially but this did not work with the STARTING NEW TASK task name option.
    Below are the codes segements I used.
    In my main program I have the following code segement
    CALL FUNCTION 'Z_CA_PROG_CALL'
      IN BACKGROUND TASK
      EXPORTING
        zprogram            = 'ZCA_TEST1'
      EXCEPTIONS
        program_call_failed = 1
        invalid             = 2
        OTHERS              = 3.
    IF sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    COMMIT WORK.
    In the function module I have the following code.
    FUNCTION z_ca_prog_call.
    ""Local interface:
    *"  IMPORTING
    *"     VALUE(ZPROGRAM) LIKE  ZCA_INTERFPROG-ZPROGRAM
    *"  EXCEPTIONS
    *"      PROGRAM_CALL_FAILED
    *"      INVALID
      SUBMIT (zprogram).
      IF sy-subrc <> 0.
        CASE sy-subrc.
          WHEN 1.
            RAISE program_call_failed.
          WHEN OTHERS.
            RAISE invalid.
        ENDCASE.
      ENDIF.
    ENDFUNCTION.

  • Using ExecutorService class from java.util.concurrent package

    Dear java programmers,
    I have a question regarding the ExecutorService class from java.util.concurrent package.
    I want to parse hundreds of files and for this purpose I'm implementing a thread pool. The way I use the ExecutorService class is summarized below:
    ExecutorService executor = Executors.newFixedThreadPool(10);
            for (int i = 0; i < 1000; i++){
                System.out.println("Parsing file No "+i);
                executor.submit(new Dock(i));
            executor.shutdown();
            try {
                executor.awaitTermination(30, TimeUnit.SECONDS);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            executor.shutdownNow();However, the code snippet above creates all the 1000 threads (Dock objects) at once and loads them to the executor, and thus I'm worrying about memory leak. I haven't tested it on 1000 files yet but just on 50 small ones, and even if the program prints out "Parsing file No "+i 50 times at once, it executes normally the threads in the background.
    I guess the write way would be to keep the number of active/idle threads in the executor constant (lets say 20 if the thread pool's size is 10) and submit a new one whenever a thread has been finished or terminated. But for this to happen the program should be notified someway whenever a thread is done. Can anybody help me do that?
    thanks in advance,
    Tom

    Ok I found a feasible solution myself although I'm not sure if this is the optimum.
    Here's what I did:
            ExecutorService executor = Executors.newFixedThreadPool(10);
            Future<String> future0, future1, future2, future3, future4, future5, future6, future7, future8, future9;
            Future[] futureArray = {future0 = null, future1 = null, future2 = null, future3 = null, future4 = null, future5 = null,
            future6 = null, future7 = null, future8 = null, future9 = null};
            for (int i = 0; i < 10; i++){
                futureArray[i] = executor.submit(new Dock(i));
            }I created the ExecutorService object which encapsulates the thread pool and then created 10 Future objects (java.util.concurrent.Future) and added them into an Array.
    For java.util.concurrent.Future and Callable Interface usage refer to:
    [http://www.swingwiki.org/best:use_worker_thread_for_long_operations]
    [http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter10/concurrencyTools.html]
    I used a Future[] Array to make the code neater. So after that I submitted -and in this way filled up- the first 10 threads to the thread pool.
            int i = 9;
            while (i < 1000){
                for (int j = 0; j < 10; j++){
                    if (futureArray[j].isDone() && i < 999){
                        try{
                            i++;
                            futureArray[j] = executor.submit(new Dock(i));
                        } catch (ExecutionException ex) {
                            ex.printStackTrace();
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                try {
                    Thread.sleep(100); // wait a while
                } catch(InterruptedException iex) { /* ignore */ }
            executor.shutdown();
            try {
                executor.awaitTermination(60, TimeUnit.SECONDS);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            executor.shutdownNow();
        }Each of the future[0-9] objects represents a thread in the thread pool. So essentially I'm check which of these 10 threads has been finished (using the java.util.concurrent.Future.isDone() method) and if yes I replenish that empty future[0-9] object with a new one.

Maybe you are looking for

  • How can i transfer the balance of iTunes form one to another if i haven't spent?

    how can i transfer the balance of iTunes form one to another if i haven't spent?

  • Connecting to the Google Mail application on a Nok...

    I've downloaded the Google Mail app but can't get it to connect to the network on my phone - after entering my user name and password I just get a message which says no network access. My phone is set up for WAP web browsing and this works fine. I'd

  • Balences Carry forward

    Hi, Here i am trying to Balance Carry forward for g.l accounts T.Code: f.16, Example: senio 1. some of the balances are nor carry forward. That balances r posted in next year.our fiscal Year is closed Dec, January we r posted some trans that can not

  • Problem in Actual assessment cycle.

    Hi Team, We are using assessment cycle to distribute the cost from utility cost center to production cost center, after cycle execution we found the cost in debit side of the production cost center with assessment cost element. And also we are using

  • Problem with internet after waking up (hp presario cq56)

    Hi. After waking up from "sleeping" state I can't connect to the internet, laptop just doesn't see the connection (wire). After rebooting everything turns back to normal. Can anyone help me? Thanks a lot! PS I'm using Gnome 3