Being thread safe means avoiding a few problems. The most common and probably the worst is called threadlock. An old analogy is the story of lunch philosophers. They are very polite and will never put out their chopsticks when someone else does the same. If they all stretch out at the same time, then they all stop at the same time and wait ... and nothing happens, because they are too polite to go first.
As someone else noted, if your application never creates additional threads, but simply starts from the main method, that is, there is only one thread or one “dining philosopher”, so the thread cannot happen. When you have multiple threads, the easiest way to avoid threadlock is to use a “monitor”, which is just an object that is set aside. In fact, your methods should get a “lock” on this monitor before accessing the threads, so there are no conflicts. However, you can still have threadlock, because there may be two objects trying to access two different threads, each with its own monitor. Object A must wait until object B releases its lock on monitor object 1; Object B must wait for Object A to release its lock on monitor object 2. So, now you are back to the streaming screen.
In short, thread safety is not very difficult to understand, but it takes time, practice and experience. The first time you write a multi-threaded application, you will come across threadlock. Then you will find out, and it will soon become quite intuitive. The biggest caveat is that you need to keep the multi-threaded part of the application as simple as possible. If you have a lot of threads, with lots of monitors and locks, it is exponentially harder to ensure that your dining philosophers never freeze.
The Java tutorial is very versed in streaming; it was the only resource i ever needed.
dnuttle
source share