Home Blog Page 3893

Swift object pool design sample



· 1 min learn


On this fast tutorial I will clarify & present you tips on how to implement the item pool design sample utilizing the Swift programming language.

A generic object pool in Swift

The object pool sample is a creational design sample. The principle thought behind it’s that first you create a set of objects (a pool), you then purchase & launch objects from the pool, as a substitute of regularly creating and releasing them. 👍

Why? Efficiency enhancements. For instance the Dispatch framework makes use of an object pool sample to offer pre-created queues for the builders, as a result of making a queue (with an related thread) is an comparatively costly operation.

One other use case of the object pool sample is employees. For instance you need to obtain a whole bunch of pictures from the net, however you’d prefer to obtain solely 5 concurrently you are able to do it with a pool of 5 employee objects. In all probability it’s going to be quite a bit cheaper to allocate a small variety of employees (that’ll truly do the obtain job), than create a brand new one for each single picture obtain request. 🖼

What concerning the downsides of this sample? There are some. For instance you probably have employees in your pool, they could include states or delicate consumer information. It’s a must to be very cautious with them aka. reset every thing. Additionally if you’re working in a multi-threaded setting you need to make your pool thread-safe.

Right here is an easy generic thread-safe object pool class:

import Basis

class Pool {

    personal let lockQueue = DispatchQueue(label: "pool.lock.queue")
    personal let semaphore: DispatchSemaphore
    personal var gadgets = [T]()

    init(_ gadgets: [T]) {
        self.semaphore = DispatchSemaphore(worth: gadgets.depend)
        self.gadgets.reserveCapacity(gadgets.depend)
        self.gadgets.append(contentsOf: gadgets)
    }

    func purchase() -> T? {
        if self.semaphore.wait(timeout: .distantFuture) == .success, !self.gadgets.isEmpty {
            return self.lockQueue.sync {
                return self.gadgets.take away(at: 0)
            }
        }
        return nil
    }

    func launch(_ merchandise: T) {
        self.lockQueue.sync {
            self.gadgets.append(merchandise)
            self.semaphore.sign()
        }
    }
}


let pool = Pool(["a", "b", "c"])

let a = pool.purchase()
print("(a ?? "n/a") acquired")
let b = pool.purchase()
print("(b ?? "n/a") acquired")
let c = pool.purchase()
print("(c ?? "n/a") acquired")

DispatchQueue.world(qos: .default).asyncAfter(deadline: .now() + .seconds(2)) {
    if let merchandise = b {
        pool.launch(merchandise)
    }
}

print("No extra useful resource within the pool, blocking thread till...")
let x = pool.purchase()
print("(x ?? "n/a") acquired once more")

As you possibly can see the implementation is just some strains. You might have the thread protected array of the generic pool gadgets, a dispatch semaphore that’ll block if there aren’t any objects out there within the pool, and two strategies so as to truly use the item pool.

Within the pattern you possibly can see that if there aren’t any extra objects left within the pool, the present queue shall be blocked till a useful resource is being freed & prepared to make use of. So be careful & don’t block the principle thread unintentionally! 😉

Associated posts


On this article I’m going to indicate you tips on how to implement a fundamental occasion processing system in your modular Swift utility.


Study the iterator design sample through the use of some customized sequences, conforming to the IteratorProtocol from the Swift commonplace library.


Discover ways to use lazy properties in Swift to enhance efficiency, keep away from optionals or simply to make the init course of extra clear.


Newbie’s information about optics in Swift. Discover ways to use lenses and prisms to govern objects utilizing a purposeful strategy.

FlightAware Information Breach Occurred Due To Configuration Error

0


The favored flight-tracking instrument FlightAware has alerted customers a few knowledge breach that has been ongoing for a number of years. FlightAware talked about a configuration error as the rationale behind the safety lapse.

FlightAware Information Breach Spans Throughout A number of Years

Reportedly, FlightAware not too long ago found an information breach involving the non-public info of its prospects. Following this discovery and the following remediation of the safety flaw, the service has now disclosed the incident info publicly.

In keeping with its breach notification, the service detected a configuration error on July 25th, 2024, which uncovered account particulars of FlightAware prospects. This consists of customers’ account passwords, electronic mail addresses, and consumer IDs.

Consequently, this account element risked customers’ private knowledge, relying upon the extent of data customers had shared. Therefore, the breached knowledge consists of customers’ names, transport addresses, contact numbers, start dates, billing info, bank card particulars, and related social media accounts. Furthermore, in accordance with the notification, the breached knowledge additionally consists of customers’ account exercise particulars, plane owned, pilot standing, and business.

Whereas such specific particulars already point out the large impression of this knowledge breach for FlightAware customers, the agency shared some extra info in a separate discover to the Workplace of the Legal professional Normal, State of California Division of Justice. As acknowledged, the breach occurred on January 1, 2021, exposing customers’ particulars for a number of years, which additionally included their Social Safety Numbers.

Customers Requested To Reset Passwords

FlightAware remedied the configuration error upon discovering the breach to cease the info publicity. Nevertheless, out of warning, the service additionally reset customers’ passwords to forestall potential unauthorized entry.

Moreover, FlightAware additionally recommends customers take ample measures to guard their private info from potential misuse and id theft. These measures embrace a proactive assessment of checking account statements and credit score evaluations, immediate studies to the FTC and legislation enforcement companies relating to any fraudulent actions, and acquiring credit score studies from the related companies, resembling Equifax or Experian, for a complete assessment.

As compensation, the flight-tracking service additionally affords affected prospects a two-year credit score monitoring service freed from price.

Tell us your ideas within the feedback.

Hacker faces 81-month jail sentence for faking his loss of life to keep away from baby help funds

0


Facepalm: A federal court docket has sentenced a deadbeat dad to 81 months in jail for hacking authorities methods to pretend his loss of life. A grand jury indicted the person in July 2023 on a number of expenses of pc fraud, aggravated identification theft, and financial institution fraud. He admitted to accessing authorities methods and registering a fraudulent loss of life certificates to keep away from paying his again baby help.

The US Legal professional’s Workplace for the Japanese District of Kentucky prosecuted Somerset resident Jesse Kipf for cybercrimes concentrating on non-public and governmental networks. It started when he manipulated loss of life data in Hawaii’s loss of life registry system, falsely itemizing himself as deceased utilizing a cast digital signature to evade paying baby help. He additionally bought entry to those networks on the darkish internet. The US Legal professional stated Kipf’s crimes resulted in almost $200,000 in damages, disrupted crucial operations, and compromised private data.

“This scheme was a cynical and harmful effort, based mostly partly on the inexcusable objective of avoiding his baby help obligations,” stated United States Legal professional Carlton S. Shier, IV. “Thankfully, by way of the wonderful work of our regulation enforcement companions, this case will function a warning to different cyber criminals, and he’ll face the results of his disgraceful conduct.”

An FBI investigation revealed that Kipf accessed and tried to promote information from networks that included a personal firm and a state authorities registry. Kipf deliberate to make use of the stolen information, which included private identification data, for additional identification theft and fraud. His scheme’s magnitude and class indicated he has important technical abilities.

Authorities additionally charged Kipf with aggravated identification theft, which carries extreme penalties due to the far-reaching penalties for victims. The indictment moreover alleged that Kipf tried to make use of the stolen identities to fill out a number of financial institution mortgage purposes. In accordance with a US Legal professional’s Workplace press launch, his actions posed important dangers to particular person victims and the integrity of monetary and governmental networks.

“Working in collaboration with our regulation enforcement companions, this defendant who hacked a wide range of pc methods and maliciously stole the identification of others for his personal private achieve, will now pay the worth,” stated FBI Particular Agent in Cost Michael E. Stansbury for the Louisville Discipline Workplace. “Victims of identification theft face lifelong affect and for that purpose, the FBI will pursue anybody silly sufficient to have interaction on this cowardly conduct.”

The court docket sentenced Kipf to 81 months in federal jail, including that he should full no less than 85 p.c of his time earlier than turning into eligible for launch. Following his incarceration, Kipf faces three years of carefully supervised parole. His penalties might have been a lot increased had he not copped a plea.

Assistant US Legal professional Kate Ok. Smith reiterated her workplace’s dedication to pursuing justice in cybercrime and identification theft instances, highlighting the significance of safeguarding digital and private data in an more and more interconnected world.

Newest leak particulars the iPhone 16 lineup’s digicam enhancements

0



New Malware PG_MEM Targets PostgreSQL Databases for Crypto Mining


Aug 22, 2024Ravie LakshmananDatabase Safety / Cryptocurrency

New Malware PG_MEM Targets PostgreSQL Databases for Crypto Mining

Cybersecurity researchers have unpacked a brand new malware pressure dubbed PG_MEM that is designed to mine cryptocurrency after brute-forcing their manner into PostgreSQL database situations.

“Brute-force assaults on Postgres contain repeatedly making an attempt to guess the database credentials till entry is gained, exploiting weak passwords,” Aqua safety researcher Assaf Morag mentioned in a technical report.

“As soon as accessed, attackers can leverage the COPY … FROM PROGRAM SQL command to execute arbitrary shell instructions on the host, permitting them to carry out malicious actions akin to information theft or deploying malware.”

Cybersecurity

The assault chain noticed by the cloud safety agency entails focusing on misconfigured PostgreSQL databases to create an administrator function in Postgres and exploiting a function known as PROGRAM to run shell instructions.

As well as, a profitable brute-force assault is adopted by the risk actor conducting preliminary reconnaissance and executing instructions to strip the “postgres” consumer of superuser permissions, thereby proscribing the privileges of different risk actors who would possibly acquire entry by way of the identical technique.

The shell instructions are chargeable for dropping two payloads from a distant server (“128.199.77[.]96”), specifically PG_MEM and PG_CORE, that are able to terminating competing processes (e.g., Kinsing), organising persistence on the host, and finally deploying the Monero cryptocurrency miner.

That is achieved by making use of a PostgreSQL command known as COPY, which permits for copying information between a file and a database desk. It significantly weaponizes a parameter generally known as PROGRAM that permits the server to run the handed command and write this system execution outcomes to the desk.

“Whereas [cryptocurrency mining] is the principle influence, at this level the attacker may run instructions, view information, and management the server,” Morag mentioned.

“This marketing campaign is exploiting web dealing with Postgres databases with weak passwords. Many organizations join their databases to the web, weak password is a results of a misconfiguration, and lack of correct id controls.”

Discovered this text fascinating? Comply with us on Twitter and LinkedIn to learn extra unique content material we submit.