Does thread used in @Scheduled annotation released to pool before finishing execution?Is ExecutorService (specifically ThreadPoolExecutor) thread safe?How Threadpool re-use Threads and how it worksDoes a finally block always get executed in Java?Impossible to make a cached thread pool with a size limit?@Scheduled & scheduler: What exactly does pool-size do?How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?How does pool size actually work with Spring's scheduled tasks?Custom thread pool in Java 8 parallel streamDoes spring @Scheduled annotated methods runs on different threads?What is the default scheduler pool size in spring-boot?Multiple Invocations of @Scheduled annotated methodRunning method using Spring @Scheduled annotation

Does adding the 'precise' tag to daggers break anything?

Is there such a thing as too inconvenient?

Why were movies shot on film shot at 24 frames per second?

Sleeping solo in a double sleeping bag

How to avoid using System.String with Rfc2898DeriveBytes in C#

Does Git delete empty folders?

The teacher logged me in as administrator for doing a short task, is the whole system now compromised?

Are required indicators necessary for radio buttons?

In an emergency, how do I find and share my position?

Taking out number of subarrays from an array which contains all the distinct elements of that array

Nuclear decay triggers

How to setup a teletype to a unix shell

(Why) May a Beit Din refuse to bury a body in order to coerce a man into giving a divorce?

Is there a SubImageApply?

Metal that glows when near pieces of itself

Thread-safe, Convenient and Performant Random Number Generator

Is a butterfly one or two animals?

How can I support the recycling, but not the new production of aluminum?

Why didn’t Doctor Strange stay in the original winning timeline?

Why don't sharp and flat root note chords seem to be present in much guitar music?

What professions would a medieval village with a population of 100 need?

Can my boyfriend, who lives in the UK and has a Polish passport, visit me in the USA?

How to compare two different formulations of a problem?

How to create a summation symbol with a vertical bar?



Does thread used in @Scheduled annotation released to pool before finishing execution?


Is ExecutorService (specifically ThreadPoolExecutor) thread safe?How Threadpool re-use Threads and how it worksDoes a finally block always get executed in Java?Impossible to make a cached thread pool with a size limit?@Scheduled & scheduler: What exactly does pool-size do?How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?How does pool size actually work with Spring's scheduled tasks?Custom thread pool in Java 8 parallel streamDoes spring @Scheduled annotated methods runs on different threads?What is the default scheduler pool size in spring-boot?Multiple Invocations of @Scheduled annotated methodRunning method using Spring @Scheduled annotation






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I have 5 @Scheduled annotated methods and pool size of my ThreadPoolTaskScheduler is 10. Annotations of my methods are the same and like this.




@Scheduled(fixedDelay = 1000, initialDelay = 10000)




My question is that;



When one of the scheduled methods gets a thread from pool and start to run; does it release the thread to pool before its execution is finished? (for example in case of context switch etc.) or this thread is used until the end of the execution?



I mean is it possible to some part of the scheduled task is done with thread-1 and some part is done with thread-2 ?










share|improve this question


























  • Do you mean pool or poll? Looks like there might be a typo

    – Alex W
    Mar 27 at 15:30











  • You will have to create another thread yourself when the scheduled method is triggered if you want part of that method to be executed in another thread.

    – Rakesh
    Mar 27 at 15:33











  • @AlexW yes it was a typo. Thx.

    – H.Ç.T
    Mar 27 at 15:35











  • @Rakesh actually I don't want to split execution to different thread. I just want to know default behavior of spring scheduler.

    – H.Ç.T
    Mar 27 at 15:37


















2















I have 5 @Scheduled annotated methods and pool size of my ThreadPoolTaskScheduler is 10. Annotations of my methods are the same and like this.




@Scheduled(fixedDelay = 1000, initialDelay = 10000)




My question is that;



When one of the scheduled methods gets a thread from pool and start to run; does it release the thread to pool before its execution is finished? (for example in case of context switch etc.) or this thread is used until the end of the execution?



I mean is it possible to some part of the scheduled task is done with thread-1 and some part is done with thread-2 ?










share|improve this question


























  • Do you mean pool or poll? Looks like there might be a typo

    – Alex W
    Mar 27 at 15:30











  • You will have to create another thread yourself when the scheduled method is triggered if you want part of that method to be executed in another thread.

    – Rakesh
    Mar 27 at 15:33











  • @AlexW yes it was a typo. Thx.

    – H.Ç.T
    Mar 27 at 15:35











  • @Rakesh actually I don't want to split execution to different thread. I just want to know default behavior of spring scheduler.

    – H.Ç.T
    Mar 27 at 15:37














2












2








2








I have 5 @Scheduled annotated methods and pool size of my ThreadPoolTaskScheduler is 10. Annotations of my methods are the same and like this.




@Scheduled(fixedDelay = 1000, initialDelay = 10000)




My question is that;



When one of the scheduled methods gets a thread from pool and start to run; does it release the thread to pool before its execution is finished? (for example in case of context switch etc.) or this thread is used until the end of the execution?



I mean is it possible to some part of the scheduled task is done with thread-1 and some part is done with thread-2 ?










share|improve this question
















I have 5 @Scheduled annotated methods and pool size of my ThreadPoolTaskScheduler is 10. Annotations of my methods are the same and like this.




@Scheduled(fixedDelay = 1000, initialDelay = 10000)




My question is that;



When one of the scheduled methods gets a thread from pool and start to run; does it release the thread to pool before its execution is finished? (for example in case of context switch etc.) or this thread is used until the end of the execution?



I mean is it possible to some part of the scheduled task is done with thread-1 and some part is done with thread-2 ?







java spring scheduled-tasks java-threads spring-scheduled






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 27 at 15:34







H.Ç.T

















asked Mar 27 at 15:28









H.Ç.TH.Ç.T

399 bronze badges




399 bronze badges















  • Do you mean pool or poll? Looks like there might be a typo

    – Alex W
    Mar 27 at 15:30











  • You will have to create another thread yourself when the scheduled method is triggered if you want part of that method to be executed in another thread.

    – Rakesh
    Mar 27 at 15:33











  • @AlexW yes it was a typo. Thx.

    – H.Ç.T
    Mar 27 at 15:35











  • @Rakesh actually I don't want to split execution to different thread. I just want to know default behavior of spring scheduler.

    – H.Ç.T
    Mar 27 at 15:37


















  • Do you mean pool or poll? Looks like there might be a typo

    – Alex W
    Mar 27 at 15:30











  • You will have to create another thread yourself when the scheduled method is triggered if you want part of that method to be executed in another thread.

    – Rakesh
    Mar 27 at 15:33











  • @AlexW yes it was a typo. Thx.

    – H.Ç.T
    Mar 27 at 15:35











  • @Rakesh actually I don't want to split execution to different thread. I just want to know default behavior of spring scheduler.

    – H.Ç.T
    Mar 27 at 15:37

















Do you mean pool or poll? Looks like there might be a typo

– Alex W
Mar 27 at 15:30





Do you mean pool or poll? Looks like there might be a typo

– Alex W
Mar 27 at 15:30













You will have to create another thread yourself when the scheduled method is triggered if you want part of that method to be executed in another thread.

– Rakesh
Mar 27 at 15:33





You will have to create another thread yourself when the scheduled method is triggered if you want part of that method to be executed in another thread.

– Rakesh
Mar 27 at 15:33













@AlexW yes it was a typo. Thx.

– H.Ç.T
Mar 27 at 15:35





@AlexW yes it was a typo. Thx.

– H.Ç.T
Mar 27 at 15:35













@Rakesh actually I don't want to split execution to different thread. I just want to know default behavior of spring scheduler.

– H.Ç.T
Mar 27 at 15:37






@Rakesh actually I don't want to split execution to different thread. I just want to know default behavior of spring scheduler.

– H.Ç.T
Mar 27 at 15:37













1 Answer
1






active

oldest

votes


















2














Threading is complicated and my understanding is not as great as others, but here's my attempt at a brief explanation of how the @Scheduled Spring annotation works:



Spring uses a TaskScheduler:



public interface TaskScheduler 

ScheduledFuture schedule(Runnable task, Trigger trigger);

ScheduledFuture schedule(Runnable task, Date startTime);

ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period);

ScheduledFuture scheduleAtFixedRate(Runnable task, long period);

ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay);

ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay);




https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html#scheduling-task-scheduler



Which submits the annotated code, i.e. task code, to a high-level concurrency object called an executor. The executor class is ThreadPoolTaskExecutor. That class submits tasks to the thread pool to be run by the first available thread in the pool. The thread pool size you set determines how many active threads you can have. If you set allowCoreThreadTimeOut to true then threads in the pool that have no work available to do within their timeout interval will be terminated.



Spring uses a ThreadPoolTaskExecutor to manage the thread pool:



https://github.com/spring-projects/spring-framework/blob/master/spring-context/src/main/java/org/springframework/scheduling/concurrent/ThreadPoolTaskExecutor.java



Keeping a pool of threads alive reduces the time that would normally be added while waiting for the thread to be created. See this question for some more info.



Ultimately, the java.lang.Thread class runs the Runnable or Callable instances that are created by the ThreadPoolTaskExecutor. The Thread class implements a run() method that is basically your code you want the thread to run:



public Thread(Runnable target) 
init(null, target, "Thread-" + nextThreadNum(), 0);


private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc) {
...


http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/lang/Thread.java



The actual switching between threads, i.e. the context switch is OS-dependent but in general threads will be divided amongst CPUs and then each CPU cycles through the threads based on the timeout interval and does a bit of work and then pauses and switches continuously between threads until the task(s) are complete.




does it release the thread to pool before its execution is finished?
(for example in case of context switch etc.) or this thread is used
until the end of the execution?




The Runnable code can definitely stop executing in the middle of an operation but the Threads in a thread pool are usually kept alive until there's no more work to be done.



Here's more info from the Oracle documentation that explains thread pools:




Most of the executor implementations in java.util.concurrent use
thread pools, which consist of worker threads. This kind of thread
exists separately from the Runnable and Callable tasks it executes and
is often used to execute multiple tasks.



Using worker threads minimizes the overhead due to thread creation.
Thread objects use a significant amount of memory, and in a
large-scale application, allocating and deallocating many thread
objects creates a significant memory management overhead.



One common type of thread pool is the fixed thread pool. This type of
pool always has a specified number of threads running; if a thread is
somehow terminated while it is still in use, it is automatically
replaced with a new thread. Tasks are submitted to the pool via an
internal queue, which holds extra tasks whenever there are more active
tasks than threads.



An important advantage of the fixed thread pool is that applications
using it degrade gracefully. To understand this, consider a web server
application where each HTTP request is handled by a separate thread.
If the application simply creates a new thread for every new HTTP
request, and the system receives more requests than it can handle
immediately, the application will suddenly stop responding to all
requests when the overhead of all those threads exceed the capacity of
the system. With a limit on the number of the threads that can be
created, the application will not be servicing HTTP requests as
quickly as they come in, but it will be servicing them as quickly as
the system can sustain.







share|improve this answer



























  • thanks for this comprehensive explanation. But I guess Spring's Scheduled annotation must have a design decision about this. (like a thread is not released until end of execution or can be released etc.) But unfortunately I cannot find it in spring documentation. Because I want to use a thread scoped spring bean in scheduled job but I want to be sure if it is safe to use it. (if thread is released then the data could be mixed with another thread's data etc.) Do you have any information about it? Is it safe to use thread scope bean in a Scheduled method?

    – H.Ç.T
    Mar 28 at 11:26











  • @H.Ç.T As far as I know, Spring doesn't take responsibility for thread safety. So, you'll have to use the normal Java methods for ensuring thread safety, e.g. volatile variables to share state, synchronized blocks to guarantee exclusivity of operations, etc. This answer has some info also.

    – Alex W
    Mar 28 at 18:53











  • Also, it's dependent on the task for whether or not it's thread-safe. If the threads are modifying a file, you'll definitely have to manage state between them. If all of the threads store their info in local memory and can do the operations concurrently without stepping on each other then there's nothing to worry about.

    – Alex W
    Mar 28 at 18:55










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55380915%2fdoes-thread-used-in-scheduled-annotation-released-to-pool-before-finishing-exec%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














Threading is complicated and my understanding is not as great as others, but here's my attempt at a brief explanation of how the @Scheduled Spring annotation works:



Spring uses a TaskScheduler:



public interface TaskScheduler 

ScheduledFuture schedule(Runnable task, Trigger trigger);

ScheduledFuture schedule(Runnable task, Date startTime);

ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period);

ScheduledFuture scheduleAtFixedRate(Runnable task, long period);

ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay);

ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay);




https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html#scheduling-task-scheduler



Which submits the annotated code, i.e. task code, to a high-level concurrency object called an executor. The executor class is ThreadPoolTaskExecutor. That class submits tasks to the thread pool to be run by the first available thread in the pool. The thread pool size you set determines how many active threads you can have. If you set allowCoreThreadTimeOut to true then threads in the pool that have no work available to do within their timeout interval will be terminated.



Spring uses a ThreadPoolTaskExecutor to manage the thread pool:



https://github.com/spring-projects/spring-framework/blob/master/spring-context/src/main/java/org/springframework/scheduling/concurrent/ThreadPoolTaskExecutor.java



Keeping a pool of threads alive reduces the time that would normally be added while waiting for the thread to be created. See this question for some more info.



Ultimately, the java.lang.Thread class runs the Runnable or Callable instances that are created by the ThreadPoolTaskExecutor. The Thread class implements a run() method that is basically your code you want the thread to run:



public Thread(Runnable target) 
init(null, target, "Thread-" + nextThreadNum(), 0);


private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc) {
...


http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/lang/Thread.java



The actual switching between threads, i.e. the context switch is OS-dependent but in general threads will be divided amongst CPUs and then each CPU cycles through the threads based on the timeout interval and does a bit of work and then pauses and switches continuously between threads until the task(s) are complete.




does it release the thread to pool before its execution is finished?
(for example in case of context switch etc.) or this thread is used
until the end of the execution?




The Runnable code can definitely stop executing in the middle of an operation but the Threads in a thread pool are usually kept alive until there's no more work to be done.



Here's more info from the Oracle documentation that explains thread pools:




Most of the executor implementations in java.util.concurrent use
thread pools, which consist of worker threads. This kind of thread
exists separately from the Runnable and Callable tasks it executes and
is often used to execute multiple tasks.



Using worker threads minimizes the overhead due to thread creation.
Thread objects use a significant amount of memory, and in a
large-scale application, allocating and deallocating many thread
objects creates a significant memory management overhead.



One common type of thread pool is the fixed thread pool. This type of
pool always has a specified number of threads running; if a thread is
somehow terminated while it is still in use, it is automatically
replaced with a new thread. Tasks are submitted to the pool via an
internal queue, which holds extra tasks whenever there are more active
tasks than threads.



An important advantage of the fixed thread pool is that applications
using it degrade gracefully. To understand this, consider a web server
application where each HTTP request is handled by a separate thread.
If the application simply creates a new thread for every new HTTP
request, and the system receives more requests than it can handle
immediately, the application will suddenly stop responding to all
requests when the overhead of all those threads exceed the capacity of
the system. With a limit on the number of the threads that can be
created, the application will not be servicing HTTP requests as
quickly as they come in, but it will be servicing them as quickly as
the system can sustain.







share|improve this answer



























  • thanks for this comprehensive explanation. But I guess Spring's Scheduled annotation must have a design decision about this. (like a thread is not released until end of execution or can be released etc.) But unfortunately I cannot find it in spring documentation. Because I want to use a thread scoped spring bean in scheduled job but I want to be sure if it is safe to use it. (if thread is released then the data could be mixed with another thread's data etc.) Do you have any information about it? Is it safe to use thread scope bean in a Scheduled method?

    – H.Ç.T
    Mar 28 at 11:26











  • @H.Ç.T As far as I know, Spring doesn't take responsibility for thread safety. So, you'll have to use the normal Java methods for ensuring thread safety, e.g. volatile variables to share state, synchronized blocks to guarantee exclusivity of operations, etc. This answer has some info also.

    – Alex W
    Mar 28 at 18:53











  • Also, it's dependent on the task for whether or not it's thread-safe. If the threads are modifying a file, you'll definitely have to manage state between them. If all of the threads store their info in local memory and can do the operations concurrently without stepping on each other then there's nothing to worry about.

    – Alex W
    Mar 28 at 18:55















2














Threading is complicated and my understanding is not as great as others, but here's my attempt at a brief explanation of how the @Scheduled Spring annotation works:



Spring uses a TaskScheduler:



public interface TaskScheduler 

ScheduledFuture schedule(Runnable task, Trigger trigger);

ScheduledFuture schedule(Runnable task, Date startTime);

ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period);

ScheduledFuture scheduleAtFixedRate(Runnable task, long period);

ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay);

ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay);




https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html#scheduling-task-scheduler



Which submits the annotated code, i.e. task code, to a high-level concurrency object called an executor. The executor class is ThreadPoolTaskExecutor. That class submits tasks to the thread pool to be run by the first available thread in the pool. The thread pool size you set determines how many active threads you can have. If you set allowCoreThreadTimeOut to true then threads in the pool that have no work available to do within their timeout interval will be terminated.



Spring uses a ThreadPoolTaskExecutor to manage the thread pool:



https://github.com/spring-projects/spring-framework/blob/master/spring-context/src/main/java/org/springframework/scheduling/concurrent/ThreadPoolTaskExecutor.java



Keeping a pool of threads alive reduces the time that would normally be added while waiting for the thread to be created. See this question for some more info.



Ultimately, the java.lang.Thread class runs the Runnable or Callable instances that are created by the ThreadPoolTaskExecutor. The Thread class implements a run() method that is basically your code you want the thread to run:



public Thread(Runnable target) 
init(null, target, "Thread-" + nextThreadNum(), 0);


private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc) {
...


http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/lang/Thread.java



The actual switching between threads, i.e. the context switch is OS-dependent but in general threads will be divided amongst CPUs and then each CPU cycles through the threads based on the timeout interval and does a bit of work and then pauses and switches continuously between threads until the task(s) are complete.




does it release the thread to pool before its execution is finished?
(for example in case of context switch etc.) or this thread is used
until the end of the execution?




The Runnable code can definitely stop executing in the middle of an operation but the Threads in a thread pool are usually kept alive until there's no more work to be done.



Here's more info from the Oracle documentation that explains thread pools:




Most of the executor implementations in java.util.concurrent use
thread pools, which consist of worker threads. This kind of thread
exists separately from the Runnable and Callable tasks it executes and
is often used to execute multiple tasks.



Using worker threads minimizes the overhead due to thread creation.
Thread objects use a significant amount of memory, and in a
large-scale application, allocating and deallocating many thread
objects creates a significant memory management overhead.



One common type of thread pool is the fixed thread pool. This type of
pool always has a specified number of threads running; if a thread is
somehow terminated while it is still in use, it is automatically
replaced with a new thread. Tasks are submitted to the pool via an
internal queue, which holds extra tasks whenever there are more active
tasks than threads.



An important advantage of the fixed thread pool is that applications
using it degrade gracefully. To understand this, consider a web server
application where each HTTP request is handled by a separate thread.
If the application simply creates a new thread for every new HTTP
request, and the system receives more requests than it can handle
immediately, the application will suddenly stop responding to all
requests when the overhead of all those threads exceed the capacity of
the system. With a limit on the number of the threads that can be
created, the application will not be servicing HTTP requests as
quickly as they come in, but it will be servicing them as quickly as
the system can sustain.







share|improve this answer



























  • thanks for this comprehensive explanation. But I guess Spring's Scheduled annotation must have a design decision about this. (like a thread is not released until end of execution or can be released etc.) But unfortunately I cannot find it in spring documentation. Because I want to use a thread scoped spring bean in scheduled job but I want to be sure if it is safe to use it. (if thread is released then the data could be mixed with another thread's data etc.) Do you have any information about it? Is it safe to use thread scope bean in a Scheduled method?

    – H.Ç.T
    Mar 28 at 11:26











  • @H.Ç.T As far as I know, Spring doesn't take responsibility for thread safety. So, you'll have to use the normal Java methods for ensuring thread safety, e.g. volatile variables to share state, synchronized blocks to guarantee exclusivity of operations, etc. This answer has some info also.

    – Alex W
    Mar 28 at 18:53











  • Also, it's dependent on the task for whether or not it's thread-safe. If the threads are modifying a file, you'll definitely have to manage state between them. If all of the threads store their info in local memory and can do the operations concurrently without stepping on each other then there's nothing to worry about.

    – Alex W
    Mar 28 at 18:55













2












2








2







Threading is complicated and my understanding is not as great as others, but here's my attempt at a brief explanation of how the @Scheduled Spring annotation works:



Spring uses a TaskScheduler:



public interface TaskScheduler 

ScheduledFuture schedule(Runnable task, Trigger trigger);

ScheduledFuture schedule(Runnable task, Date startTime);

ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period);

ScheduledFuture scheduleAtFixedRate(Runnable task, long period);

ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay);

ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay);




https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html#scheduling-task-scheduler



Which submits the annotated code, i.e. task code, to a high-level concurrency object called an executor. The executor class is ThreadPoolTaskExecutor. That class submits tasks to the thread pool to be run by the first available thread in the pool. The thread pool size you set determines how many active threads you can have. If you set allowCoreThreadTimeOut to true then threads in the pool that have no work available to do within their timeout interval will be terminated.



Spring uses a ThreadPoolTaskExecutor to manage the thread pool:



https://github.com/spring-projects/spring-framework/blob/master/spring-context/src/main/java/org/springframework/scheduling/concurrent/ThreadPoolTaskExecutor.java



Keeping a pool of threads alive reduces the time that would normally be added while waiting for the thread to be created. See this question for some more info.



Ultimately, the java.lang.Thread class runs the Runnable or Callable instances that are created by the ThreadPoolTaskExecutor. The Thread class implements a run() method that is basically your code you want the thread to run:



public Thread(Runnable target) 
init(null, target, "Thread-" + nextThreadNum(), 0);


private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc) {
...


http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/lang/Thread.java



The actual switching between threads, i.e. the context switch is OS-dependent but in general threads will be divided amongst CPUs and then each CPU cycles through the threads based on the timeout interval and does a bit of work and then pauses and switches continuously between threads until the task(s) are complete.




does it release the thread to pool before its execution is finished?
(for example in case of context switch etc.) or this thread is used
until the end of the execution?




The Runnable code can definitely stop executing in the middle of an operation but the Threads in a thread pool are usually kept alive until there's no more work to be done.



Here's more info from the Oracle documentation that explains thread pools:




Most of the executor implementations in java.util.concurrent use
thread pools, which consist of worker threads. This kind of thread
exists separately from the Runnable and Callable tasks it executes and
is often used to execute multiple tasks.



Using worker threads minimizes the overhead due to thread creation.
Thread objects use a significant amount of memory, and in a
large-scale application, allocating and deallocating many thread
objects creates a significant memory management overhead.



One common type of thread pool is the fixed thread pool. This type of
pool always has a specified number of threads running; if a thread is
somehow terminated while it is still in use, it is automatically
replaced with a new thread. Tasks are submitted to the pool via an
internal queue, which holds extra tasks whenever there are more active
tasks than threads.



An important advantage of the fixed thread pool is that applications
using it degrade gracefully. To understand this, consider a web server
application where each HTTP request is handled by a separate thread.
If the application simply creates a new thread for every new HTTP
request, and the system receives more requests than it can handle
immediately, the application will suddenly stop responding to all
requests when the overhead of all those threads exceed the capacity of
the system. With a limit on the number of the threads that can be
created, the application will not be servicing HTTP requests as
quickly as they come in, but it will be servicing them as quickly as
the system can sustain.







share|improve this answer















Threading is complicated and my understanding is not as great as others, but here's my attempt at a brief explanation of how the @Scheduled Spring annotation works:



Spring uses a TaskScheduler:



public interface TaskScheduler 

ScheduledFuture schedule(Runnable task, Trigger trigger);

ScheduledFuture schedule(Runnable task, Date startTime);

ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period);

ScheduledFuture scheduleAtFixedRate(Runnable task, long period);

ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay);

ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay);




https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html#scheduling-task-scheduler



Which submits the annotated code, i.e. task code, to a high-level concurrency object called an executor. The executor class is ThreadPoolTaskExecutor. That class submits tasks to the thread pool to be run by the first available thread in the pool. The thread pool size you set determines how many active threads you can have. If you set allowCoreThreadTimeOut to true then threads in the pool that have no work available to do within their timeout interval will be terminated.



Spring uses a ThreadPoolTaskExecutor to manage the thread pool:



https://github.com/spring-projects/spring-framework/blob/master/spring-context/src/main/java/org/springframework/scheduling/concurrent/ThreadPoolTaskExecutor.java



Keeping a pool of threads alive reduces the time that would normally be added while waiting for the thread to be created. See this question for some more info.



Ultimately, the java.lang.Thread class runs the Runnable or Callable instances that are created by the ThreadPoolTaskExecutor. The Thread class implements a run() method that is basically your code you want the thread to run:



public Thread(Runnable target) 
init(null, target, "Thread-" + nextThreadNum(), 0);


private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc) {
...


http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/lang/Thread.java



The actual switching between threads, i.e. the context switch is OS-dependent but in general threads will be divided amongst CPUs and then each CPU cycles through the threads based on the timeout interval and does a bit of work and then pauses and switches continuously between threads until the task(s) are complete.




does it release the thread to pool before its execution is finished?
(for example in case of context switch etc.) or this thread is used
until the end of the execution?




The Runnable code can definitely stop executing in the middle of an operation but the Threads in a thread pool are usually kept alive until there's no more work to be done.



Here's more info from the Oracle documentation that explains thread pools:




Most of the executor implementations in java.util.concurrent use
thread pools, which consist of worker threads. This kind of thread
exists separately from the Runnable and Callable tasks it executes and
is often used to execute multiple tasks.



Using worker threads minimizes the overhead due to thread creation.
Thread objects use a significant amount of memory, and in a
large-scale application, allocating and deallocating many thread
objects creates a significant memory management overhead.



One common type of thread pool is the fixed thread pool. This type of
pool always has a specified number of threads running; if a thread is
somehow terminated while it is still in use, it is automatically
replaced with a new thread. Tasks are submitted to the pool via an
internal queue, which holds extra tasks whenever there are more active
tasks than threads.



An important advantage of the fixed thread pool is that applications
using it degrade gracefully. To understand this, consider a web server
application where each HTTP request is handled by a separate thread.
If the application simply creates a new thread for every new HTTP
request, and the system receives more requests than it can handle
immediately, the application will suddenly stop responding to all
requests when the overhead of all those threads exceed the capacity of
the system. With a limit on the number of the threads that can be
created, the application will not be servicing HTTP requests as
quickly as they come in, but it will be servicing them as quickly as
the system can sustain.








share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 27 at 17:55

























answered Mar 27 at 17:32









Alex WAlex W

28.9k7 gold badges71 silver badges86 bronze badges




28.9k7 gold badges71 silver badges86 bronze badges















  • thanks for this comprehensive explanation. But I guess Spring's Scheduled annotation must have a design decision about this. (like a thread is not released until end of execution or can be released etc.) But unfortunately I cannot find it in spring documentation. Because I want to use a thread scoped spring bean in scheduled job but I want to be sure if it is safe to use it. (if thread is released then the data could be mixed with another thread's data etc.) Do you have any information about it? Is it safe to use thread scope bean in a Scheduled method?

    – H.Ç.T
    Mar 28 at 11:26











  • @H.Ç.T As far as I know, Spring doesn't take responsibility for thread safety. So, you'll have to use the normal Java methods for ensuring thread safety, e.g. volatile variables to share state, synchronized blocks to guarantee exclusivity of operations, etc. This answer has some info also.

    – Alex W
    Mar 28 at 18:53











  • Also, it's dependent on the task for whether or not it's thread-safe. If the threads are modifying a file, you'll definitely have to manage state between them. If all of the threads store their info in local memory and can do the operations concurrently without stepping on each other then there's nothing to worry about.

    – Alex W
    Mar 28 at 18:55

















  • thanks for this comprehensive explanation. But I guess Spring's Scheduled annotation must have a design decision about this. (like a thread is not released until end of execution or can be released etc.) But unfortunately I cannot find it in spring documentation. Because I want to use a thread scoped spring bean in scheduled job but I want to be sure if it is safe to use it. (if thread is released then the data could be mixed with another thread's data etc.) Do you have any information about it? Is it safe to use thread scope bean in a Scheduled method?

    – H.Ç.T
    Mar 28 at 11:26











  • @H.Ç.T As far as I know, Spring doesn't take responsibility for thread safety. So, you'll have to use the normal Java methods for ensuring thread safety, e.g. volatile variables to share state, synchronized blocks to guarantee exclusivity of operations, etc. This answer has some info also.

    – Alex W
    Mar 28 at 18:53











  • Also, it's dependent on the task for whether or not it's thread-safe. If the threads are modifying a file, you'll definitely have to manage state between them. If all of the threads store their info in local memory and can do the operations concurrently without stepping on each other then there's nothing to worry about.

    – Alex W
    Mar 28 at 18:55
















thanks for this comprehensive explanation. But I guess Spring's Scheduled annotation must have a design decision about this. (like a thread is not released until end of execution or can be released etc.) But unfortunately I cannot find it in spring documentation. Because I want to use a thread scoped spring bean in scheduled job but I want to be sure if it is safe to use it. (if thread is released then the data could be mixed with another thread's data etc.) Do you have any information about it? Is it safe to use thread scope bean in a Scheduled method?

– H.Ç.T
Mar 28 at 11:26





thanks for this comprehensive explanation. But I guess Spring's Scheduled annotation must have a design decision about this. (like a thread is not released until end of execution or can be released etc.) But unfortunately I cannot find it in spring documentation. Because I want to use a thread scoped spring bean in scheduled job but I want to be sure if it is safe to use it. (if thread is released then the data could be mixed with another thread's data etc.) Do you have any information about it? Is it safe to use thread scope bean in a Scheduled method?

– H.Ç.T
Mar 28 at 11:26













@H.Ç.T As far as I know, Spring doesn't take responsibility for thread safety. So, you'll have to use the normal Java methods for ensuring thread safety, e.g. volatile variables to share state, synchronized blocks to guarantee exclusivity of operations, etc. This answer has some info also.

– Alex W
Mar 28 at 18:53





@H.Ç.T As far as I know, Spring doesn't take responsibility for thread safety. So, you'll have to use the normal Java methods for ensuring thread safety, e.g. volatile variables to share state, synchronized blocks to guarantee exclusivity of operations, etc. This answer has some info also.

– Alex W
Mar 28 at 18:53













Also, it's dependent on the task for whether or not it's thread-safe. If the threads are modifying a file, you'll definitely have to manage state between them. If all of the threads store their info in local memory and can do the operations concurrently without stepping on each other then there's nothing to worry about.

– Alex W
Mar 28 at 18:55





Also, it's dependent on the task for whether or not it's thread-safe. If the threads are modifying a file, you'll definitely have to manage state between them. If all of the threads store their info in local memory and can do the operations concurrently without stepping on each other then there's nothing to worry about.

– Alex W
Mar 28 at 18:55






Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55380915%2fdoes-thread-used-in-scheduled-annotation-released-to-pool-before-finishing-exec%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript