Archives
Trending
Support
Login
clear text
XML
Django
JavaScript
MATLAB
C
C++
C#
Python
SQL
Shell
Bash
Markdown
YAML
JSON
HTML
CSS
PHP
Java
Ruby
Go
Rust
Swift
Kotlin
Arduino
TypeScript
Perl
Autohotkey
Lua
SQF
R
Scala
Haskell
Groovy
Dart
Clojure
VB.NET
Objective-C
PowerShell
Bash
CoffeeScript
Verilog
import java.util.*; import java.util.concurrent.Semaphore; public class Singleton { private static volatile Singleton singleton; static Semaphore semaphore; private Singleton() { semaphore = new Semaphore(1); } public Singleton getInstance() throws InterruptedException{ // TODO: 3/29/20 Synchronize this semaphore.acquire(); if(singleton == null) { System.out.println("created singleton"); singleton = new Singleton(); } semaphore.release(); return singleton; } public static void main(String[] args) { // TODO: 3/29/20 Simulate the scenario when multiple threads call the method getInstance List
list = new ArrayList<>(); Singleton s = new Singleton(); for(int i = 0; i < 20; i++) { list.add(new Thread(new Runnable() { @Override public void run() { try { s.getInstance(); } catch (InterruptedException e) { } } })); } for(int i = 0; i < 20; i++) { list.get(i).start(); } for(int i = 0; i < 20; i++) { try { list.get(i).join(); } catch (InterruptedException e) { System.out.println(e); } } } }
Mark as private (unlisted)
for 30 minutes
for 6 hours
for 1 day
for 1 week
for 1 month
for 1 year
everlasting (like CCCP)