User Tools

Site Tools


programming:java:multithreading

Multithreading

What Where
Introduction vogella
Whereever possible use the safe Structures from concurrent package

PitFalls

  1. Do not use TimeStamps to synchronize Threads. Therere can be more than 1 action every millisecond - what to do with equal TimeStamps?

Concurrent Package

Das Concurrent Package bietet viele fertige Multithreading Klassen.

Class What
Timer Can execute TimerTasks(Runnables) after a Timeout. Can be canceled only once.
Future Can compute something asynchronously. The result, when ready, is available throught get()

ForkJoin

A framework to execute parallel task. The mechanism is described here.

Display.readAndDispatch()

//A nice way to stop the UI thread, in order to wait for a job, without blocking the UI Jobs coming from other Threads
while(job.getResult()==null) {
  Display.getDefault().readAndDispatch();
}

Try-Catch is Bypassed in nested threads

On every thread there should be an own Exception-handling. Putting a new Thread creation into try-catch block won't catch the Exceptions.

		//ATTENTION: the exception is not catched!
		try{
			Runnable r = new Runnable() {
				
				@Override
				public void run() {
					System.out.println("Thread");
					
					Display.getDefault().syncExec(new Runnable() {
	                    @Override
	                    public void run() {
	                    	System.out.println("ThreadGUI");
	                    	throw new NullPointerException();
	                    }
	                });
					
				}
			};
			
			Thread t = new Thread(r);
			t.start();

		}catch(NullPointerException e){
			//nothing
		}
		
		System.out.println("Ende");

programming/java/multithreading.txt · Last modified: 2023/11/01 07:31 by skipidar