Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Comparison of C Sharp and Java
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== Threading and asynchronous features == Both languages include [[Thread (computing)|thread]] [[synchronization]] mechanisms as part of their language syntax. {| class="wikitable" style="width:80%;" |- ! style="width:40%;"| [[Thread (computer science)|Threading]] and [[Synchronization (computer science)|Synchronization]] !! style="width:30%;"|Java !! style="width:30%;"|C# |- |Threads || {{yes}} || {{yes}} |- |[[Thread pool pattern|Thread pool]] || {{yes}} || {{yes}} |- |Task-based parallelism || {{yes}}<ref>Fork-join framework included with Java version 7. {{cite web |url=http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ForkJoinPool.html |title=ForkJoinPool (Java Platform SE 7 ) |publisher=Oracle |access-date=17 July 2015}}</ref> || {{yes}}<ref>{{cite web |url=http://msdn.microsoft.com/en-us/library/dd460717.aspx |title=Task Parallel Library (TPL) |publisher=Msdn.microsoft.com |date=18 February 2015 |access-date=24 February 2015}}</ref> |- |[[Semaphore (programming)|Semaphores]] || {{yes}} || {{yes}} |- |[[Monitor (synchronization)|Monitors]] || {{yes}} || {{yes}} |- |Thread-local variables || {{yes}} || {{yes}}; {{mono|ThreadStaticAttribute}} and {{code|ThreadLocal<T>}} class |} === Task-based parallelism for C# === With .NET Framework 4.0, a new task-based programming model was introduced to replace the existing event-based asynchronous model. The API is based around the {{mono|Task}} and {{code|Task<T>}} classes. Tasks can be composed and chained. By convention, every method that returns a {{mono|Task}} should have its name postfixed with ''Async''. <syntaxhighlight lang="csharp"> public static class SomeAsyncCode { public static Task<XDocument> GetContentAsync() { HttpClient httpClient = new HttpClient(); return httpClient.GetStringAsync("www.contoso.com").ContinueWith((task) => { string responseBodyAsText = task.Result; return XDocument.Parse(responseBodyAsText); }); } } var t = SomeAsyncCode.GetContentAsync().ContinueWith((task) => { var xmlDocument = task.Result; }); t.Start(); </syntaxhighlight> In C# 5 a set of language and compiler extensions was introduced to make it easier to work with the task model. These language extensions included the notion of {{mono|async}} methods and the {{mono|await}} statement that make the program flow appear synchronous. <syntaxhighlight lang="csharp"> public static class SomeAsyncCode { public static async Task<XDocument> GetContentAsync() { HttpClient httpClient = new HttpClient(); string responseBodyAsText = await httpClient.GetStringAsync("www.contoso.com"); return XDocument.Parse(responseBodyAsText); } } var xmlDocument = await SomeAsyncCode.GetContentAsync(); // The Task will be started on call with await. </syntaxhighlight> From this [[syntactic sugar]] the C# compiler generates a state-machine that handles the necessary continuations without developers having to think about it. === Task-based parallelism for Java === Java supports threads since JDK 1.0. Java offers a high versatility for running threads, often called tasks. This is done by implementing a functional interface (a {{Javadoc:SE|package=java.lang|java/lang|Runnable}} interface) defining a single void no-args method as demonstrated in the following example: <syntaxhighlight lang="Java" line> var myThread = new Thread(() -> { var threadName = Thread.currentThread().getName(); System.out.println("Hello " + threadName); }); myThread.start(); </syntaxhighlight> Similar to C#, Java has a higher level mechanism for working with threads. {{mono|Executors}} can execute asynchronous tasks and also manage a group of subprocesses. All the threads of an {{mono|ExecutorServices}} instance are handled in a [[Pool (computer science)|pool]]. This {{mono|ExecutorService}} instance will be reused under the hood for revenant tasks, so it's possible runs as many concurrent tasks as the programmer wants throughout the life-cycle of the application using a single executor service instance. This is how the first thread-example looks using executors: <syntaxhighlight lang="Java" line> ExecutorService executor = Executors.newSingleThreadExecutor(); executor.submit(() -> { var threadName = Thread.currentThread().getName(); System.out.println("Hello " + threadName); }); </syntaxhighlight> The {{mono|ExecutorService}} instance also supports a {{mono|Callable}} interface, another single method interface like {{mono|Runnable}} but the signature of the contained method of {{mono|Callable}} returns a value. In this way, the lambda expression must also return a value, like the below example of calling a website asynchronously as the C# example. <syntaxhighlight lang="Java" line> ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> contentAsync = executor.submit(() -> { HttpRequest httpReq = HttpRequest.newBuilder() .uri(new URI("www.graalvm.org")) .build(); return HttpClient.newHttpClient() .send(httpReq, BodyHandlers.ofString()) .body(); }); var webPageResult = contentAsync.get(); </syntaxhighlight> Calling the method {{code|get()}} blocks the current thread and waits until the callable completes before returning the value (in the example, a web page content): The following example, a method and a class are used. This wrap it's just to be similar to the C# example since Java does not have keywords like async for the method signature. <syntaxhighlight lang="Java" line> public static class SomeAsyncCode { static ExecutorService executor = Executors.newSingleThreadExecutor(); public static Future<String> getContentAsync(){ return executor.submit(() -> { HttpRequest httpReq = HttpRequest.newBuilder() .uri(new URI("www.graalvm.org")) .build(); return HttpClient.newHttpClient() .send(httpReq, BodyHandlers.ofString()) .body(); }); } } var webPageResult = SomeAsyncCode.getContentAsync().get(); </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)